繁体   English   中英

为什么调用此函数会改变我的数组?

[英]Why does calling this function change my array?

每当我读取文件时,Perl似乎都在杀死我的数组:

my @files = ("foo", "bar", "baz");
print "Files: " . join(" ", @files) . "\n";

foreach(@files) {
   print "The file is $_\n";
   func();
}

sub func {
   open(READ, "< test.txt");
   while(<READ>) {
   }
   close READ;
}

print "Files: " . join(" ", @files) . "\n";

生产:

Files: foo bar baz
The file is foo
The file is bar
The file is baz
Files:

但是当我注释掉func() ,它给出了我所期望的:

Files: foo bar baz
The file is foo
The file is bar
The file is baz
Files: foo bar baz

任何想法为什么会这样?

你必须改变foo来本地化$_ ,或者不要在你的循环中使用$_ 最好的,做到两个:

foreach my $filename (@files) {
    print "The file is $filename\n";
    func();
}

sub func {
    local $_;
    open my $read, '<', 'test.txt' or die "Couldn't open test.txt: $!";
    while(<$read>) {
    }
    close $read or die "Couldn't close file: $!";
}

foreach循环将$_替换$_文件的当前名称, while(<READ>)指定给$_ 这就是魔术的糟糕组合,可以这么说。

一般来说,除了单行之外,依靠$_任何事情都是一个坏主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM