【问题标题】:Why does Perl read only half of lines in file?为什么 Perl 只读取文件中的一半行?
【发布时间】:2012-12-21 04:25:06
【问题描述】:

我想逐行读取文件,并为每一行拆分字符串并打印它。但是脚本只打印偶数行。

文件:

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

【问题讨论】:

    标签: string perl file split line


    【解决方案1】:

    这是因为你每循环读取两行

    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;
    }
    

    【讨论】:

      【解决方案2】:

      &lt;$FILE&gt; 将读取一行。您在 while 中读取一行,然后在 split 中读取另一行。

      【讨论】:

        【解决方案3】:

        因为你在 while 中读取了 1 行,而在拆分时读取了另一行。

        【讨论】:

          【解决方案4】:

          小错误。 您在 while 中读取一行,在下一个直接行中读取另一行(使用 split 的地方)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-22
            • 1970-01-01
            相关资源
            最近更新 更多