2016-09-07 57 views
-3

試圖運行代碼:在Unix上運行perl中的foreach x(cat file)?

foreach x (`cat file`) 
echo $x 
end 

預期輸出:

1 
2 
3 
4 
5 

當perl腳本運行:

1 2 3 4 5 

請告知如何實現像輸出在Perl中的unix?

+0

是您的foreach''...代碼運行?它是'perl'還是'shell-script'? – sat

+0

該語法不是Perl。我不確定它是什麼。 – Schwern

回答

0

你的代碼是不是即使在Perl

foreach x (`cat file`) 
echo $x 
end 
  1. 在Perl有沒有回聲或結束命令。
  2. 你爲什麼使用系統的cat命令?你應該使用純Perl來完成這些簡單的任務。

我假設您試圖循環播放文件的內容,然後打印每一行。

在Perl中,你可以使用下面的做到這一點:

#!/usr/bin/perl 
#always use the below 2 lines in your Perl program 
use strict; 
use warnings; 

my $filename = '/path/to/file'; 
#open file in read mode 
open (my $fh, "<", $filename) or die "Could not open file $!"; 
#use while to iterate over each line 
while my $line (<$fh>){ 
    print $line; 
} 

或者你也可以採取在一個數組文件的內容,然後遍歷它

my @lines = <$fh>; 
foreach my $line (@lines){ 
    print $line; 
} 
+0

downvote的原因是什麼? –

0

請檢查下面的代碼:

  • 我想你想在新行打印元素。你只需要添加新的行字符與元素。

@array = (1..10); 
foreach my $x (@array) 
{ 
    print "$x\n"; 
} 

輸出:

C:\Users\dinesh_pundkar\Desktop>perl a.pl 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
+0

@newbph - 請讓我知道這是否適合你。 –