在您的循环条件下,您将整个文件读入它们的数组。然后将列表分配用作布尔值。这仅适用于一次,因为在评估条件后将读取文件。此外,循环内的 readlines 将返回 undef。
这是应该工作的代码:
my (@lines_1, @lines_2);
# read until one file hits EOF
while (!eof $INFILE_1 and !eof $INFILE_2) {
my $line1 = <$INFILE_1>;
my $line2 = <$INFILE_2>;
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
push @lines_1, $line1;
push @lines_2, $line2;
}
你也可以这样做:
my (@lines_1, @lines_2);
# read while both files return strings
while (defined(my $line1 = <$INFILE_1>) and defined(my $line2 = <$INFILE_2>)) {
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
push @lines_1, $line1;
push @lines_2, $line2;
}
或者:
# read once into arrays
my @lines_1 = <$INFILE_1>;
my @lines_2 = <$INFILE_2>;
my $min_size = $#lines_1 < $#lines_2 ? $#lines_1 : $#lines_2; # $#foo is last index of @foo
# then interate over data
for my $i ( 0 .. $min_size) {
my ($line1, $line2) = ($lines_1[$i], $lines_2[$i]);
say "from the 1st file: $line1";
say "from the 2nd file: $line2";
}
当然,我假设你做了use strict; use warnings;
and use feature 'say'
,并使用了 3-arg 形式的open
词法文件句柄:
my ($file_1, $file_2) = @ARGV;
open my $INFILE_1, '<', $file_1 or die "Can't open $file_1: $!"; # also, provide the actual error!
open my $INFILE_2, '<', $file_2 or die "Can't open $file_2: $!";
我还敦促您使用描述性变量名称而不是单个字母,并在最内部的可能范围内声明您的变量——在开头声明 vars 几乎与使用糟糕的、糟糕的全局变量相同。