2013-01-07 32 views
1

我想逐行阅读一个文件,并为每一行分割字符串并打印出来。但脚本只打印偶数行。为什么Perl只读取文件中的一半行?

文件:

line1:item1 
line2:item2 
line3:item3 
line4:item4 
line5:item5 
line6:item6 

和脚本:

$FILE = "file"; 
open($FILE, "<", "file") or die("Could not open file."); 

while (<$FILE>) { 
    my $number = (split ":", <$FILE>)[1]; 
    print $number; 
} 

输出:

item2 
item4 
item6 

回答

17

这是因为你读每个回路两行轮

while (<$FILE>) { # read lines 1, 3, 5 
    my $number = (split ":", <$FILE>)[1]; # read lines 2, 4, 6 
    print $number; 
} 

使用这个代替

while (<$FILE>) { 
    my $number = (split /:/)[1]; 
    print $number; 
} 
4

<$FILE>将读取一行。你读一行,另一行分开。

0

因为您在分隔时读取了1行而另一个分隔了。

0

小错误。 您在while中读取一行,在另一个立即行中读取另一行(使用拆分)。

相关问题