【问题标题】:array elements gets deleted when looping files循环文件时数组元素被删除
【发布时间】:2019-09-05 12:44:48
【问题描述】:

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

代码:

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

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

【问题讨论】:

  • 已更正,+ 添加文件内容

标签: loops perl file-handling


【解决方案1】:
while (<$fh>)

简称

while ($_ = <$fh>)

所以你正在破坏$_,它被别名为@files 的元素。你需要保护$_如下:

while (local $_ = <$fh>)

更好的是,使用不同的变量名。

while (my $line = <$fh>)

【讨论】:

【解决方案2】:

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

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

您可以想象您当前的代码在读取每个文件后执行此操作:

for (@files) {
   undef $_;
}

【讨论】:

  • 这也是我的解决方法。另一种是使用@lines = 将文件添加到数组中。谢谢。
猜你喜欢
  • 2012-02-15
  • 2022-10-21
  • 2010-12-29
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多