循环文件时数组元素被删除

5

我在遍历文件名时遇到了问题,我的输入数组元素被删除了。

代码:

use Data::Dumper;
use warnings;
use strict;


my @files = ("file1", "file2", "file3");

print Dumper(\@files);

for (@files) {
        my $filename = $_ . '.txt';
        open(my $fh, '<:encoding(UTF-8)', $filename)
          or die "Could not open file '$filename' $!";
        while(<$fh>) {
                print "$filename read line \n";
        }
}
print Dumper(\@files);

输出:

$VAR1 = [
          'file1',
          'file2',
          'file3'
        ];
file1.txt read line
file2.txt read line
file3.txt read line
$VAR1 = [
          undef,
          undef,
          undef
        ];

文件内容:

 cat file1.txt
asdfsdfs
 cat file2.txt
iasdfasdsf
 cat file3.txt
sadflkjasdlfj

为什么数组内容会被删除? (我有两种不同的解决方法,但我想了解这段代码的问题在哪里。)

已更正,+添加文件内容 - gmezos
2个回答

7
while (<$fh>)

缩写为

while ($_ = <$fh>)

所以你正在破坏 $_,它是一个指向@files中元素的别名。你需要按照以下方式保护 $_

while (local $_ = <$fh>)

最好使用不同的变量名。
while (my $line = <$fh>)

我在这里也找到了解决方案:https://perldoc.perl.org/perlop.html#I%2fO-Operators 谢谢! - gmezos

4

在循环内部,您以两种不同的方式使用$_(作为当前文件名和当前行),它们会相互冲突。不要这样做。请为变量命名,例如:

for my $file (@files) {
    ...
    while(my $line = <$fh>) {
        ...
    }
}

您可以想象,在读取每个文件后,您的当前代码会执行以下操作:
for (@files) {
   undef $_;
}

那也是我的解决方法。另一个方法是使用@lines = <$fh>将文件读入数组中。谢谢。 - gmezos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接