2010-12-22 181 views
50

我有一个简单的Perl脚本来逐行读取文件。代码如下。我想显示两行并打破循环。但它不起作用。错误在哪里?Perl逐行读取

$file='SnPmaster.txt'; 
open(INFO, $file) or die("Could not open file."); 

$count = 0; 
foreach $line (<INFO>) { 
    print $line;  
    if ($++counter == 2){ 
     last; 
    } 
} 
close(INFO); 
+10

`use strict;使用警告;`会解决你所有的问题。 – 2010-12-22 01:11:29

+7

解析为`($ + +'counter')== 2` – 2010-12-22 01:44:37

+0

请不要再使用旧式的FILEHANDLES。 – 2014-05-23 14:50:23

回答

100

如果你已经use strict打开,你会发现,$++foo不作任何意义。

这里是如何做到这一点:

use strict; 
use warnings; 

my $file = 'SnPmaster.txt'; 
open my $info, $file or die "Could not open $file: $!"; 

while(my $line = <$info>) { 
    print $line;  
    last if $. == 2; 
} 

close $info; 

这需要特殊的变量$.它记录在当前文件中的行数的优势。 (见perlvar

如果你想用一个计数器来代替,使用

my $count = 0; 
while(my $line = <$info>) { 
    print $line;  
    last if ++$count == 2; 
} 
5

你需要使用++$counter$++counter,因此它是不工作的原因..

+4

此外,OP初始化`$ count`,然后尝试增加`$ counter`,这只能用,因为OP不使用`strict`或`warnings`。 – 2010-12-22 01:11:02

-4
#!/usr/bin/perl 
use utf8      ; 
use 5.10.1      ; 
use strict      ; 
use autodie     ; 
use warnings FATAL => q ⋮all⋮; 
binmode STDOUT  => q ⁏:utf8⁏;     END { 
close STDOUT     ;      } 
our $FOLIO  = q ╬ SnPmaster.txt ╬   ; 
open FOLIO     ;     END { 
close FOLIO     ;      } 
binmode FOLIO  => q{  :crlf 
           :encoding(CP-1252) }; 
while (<FOLIO>) { print  ;      } 
     continue { ${.} ^015^ __LINE__ || exit } 
                                                               __END__ 
unlink $FOLIO     ; 
unlink ~$HOME || 
    clri ~$HOME     ; 
reboot       ; 
11

使用这些类型的复杂程序,这是更好地让Perl中为您生成的Perl代码:

$ perl -MO=Deparse -pe'exit if $.>2' 

哪位高兴告诉你答案,

LINE: while (defined($_ = <ARGV>)) { 
    exit if $. > 2; 
} 
continue { 
    die "-p destination: $!\n" unless print $_; 
} 

或者,可以简单地从命令行运行它是这样,

$ perl -pe'exit if$.>2' file.txt 
0

在bash foo是变量的名称,以及$是操作者,这意味着“得到”的值。

perl $foo是变量的名称。