ループ状態では、ファイル全体を配列に読み込みます。リストの割り当ては、ブール値として使用されます。条件が評価された後にファイルが読み取られるため、これは1回だけ機能します。また、ループ内の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";
}
もちろん、私はあなたがそうし、そして字句ファイルハンドルでの3引数形式を使用したuse strict; use warnings;
と仮定しています:use feature 'say'
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: $!";
また、1文字ではなく説明的な変数名を使用し、可能な限り最も内側のスコープで変数を宣言することをお勧めします。最初に変数を宣言することは、悪い、悪いグローバルを使用することとほとんど同じです。