[英]Perl read line by line
I have a simple Perl script to read a file line by line. 我有一个简单的Perl脚本来逐行读取文件。 Code is below.
代码如下。 I want to display two lines and break the loop.
我想显示两行并打破循环。 But it doesn't work.
但它不起作用。 Where is the bug?
这个bug在哪里?
$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);
If you had use strict
turned on, you would have found out that $++foo
doesn't make any sense. 如果你
use strict
打开,你会发现$++foo
没有任何意义。
Here's how to do it: 这是怎么做的:
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;
This takes advantage of the special variable $.
这利用了特殊变量
$.
which keeps track of the line number in the current file. 它跟踪当前文件中的行号。 (See perlvar )
(见perlvar )
If you want to use a counter instead, use 如果您想使用计数器,请使用
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
With these types of complex programs, it's better to let Perl generate the Perl code for you: 使用这些类型的复杂程序,最好让Perl为您生成Perl代码:
$ perl -MO=Deparse -pe'exit if $.>2'
Which will gladly tell you the answer, 哪位高兴地告诉你答案,
LINE: while (defined($_ = <ARGV>)) {
exit if $. > 2;
}
continue {
die "-p destination: $!\n" unless print $_;
}
Alternatively, you can simply run it as such from the command line, 或者,您可以从命令行简单地运行它,
$ perl -pe'exit if$.>2' file.txt
你需要使用++$counter
, 而不是 $++counter
,因此它不工作的原因..
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'. 在bash中
foo
是变量的名称, $
是一个运算符,意思是'获取'的值。
In perl $foo
is the name of the variable. 在perl
$foo
是变量的名称。
#!/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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.