Perl 默认变量 $_

标签 perl

我以为我了解 map ,但是以下结果我不明白。我知道它为什么会发生,我只是不知道它是如何发生的。

问题是@array 的内容正在改变,因为 $_正在_do_stuff_to_file期间被重置称呼。所以打印的是here: \nhere:\n当我期望它是 here: donkie\nhere: kong\n .

注:这不是经过测试的代码。这只是我记得从实验室看到的。为什么@array的内容是改变?

如果我设置 $_$f在从 _some_func 返回 1 之前.然后阵列仍然完好无损。

这是一个示例程序来说明我所看到的:

my @array = ("donkie", "kong");
map { push @junk, _some_func('blah', $_); } @array;

if (join ('', @junk) !~ /0/)
{   # for example sake this is always true since return 1 from _some_func.
    print map { "here: $_\n"; } @array;
}

sub _some_func
{   # for example sake, lets say $f always exists as a file.
    my $j = shift;
    my $f = shift;
    return 0 if !open(FILE, "< $f");
    close FILE;
    _do_stuff_to_file($f);

    return 1;
}


sub _do_stuff_to_file
{
    my $f = shift;
    open(IN, "< $f");
    open(OUT, "> $f.new");

    while (<IN>)
    {
        print OUT;
    }

    close IN;
    close OUT;
}

最佳答案

Perl 中的许多函数使用默认变量 $_ .其中包括 map和 readline 运算符 <> .赞 foreach , map使循环变量成为它处理的列表中每个元素的别名。发生的事情是这一行:

while (<IN>)

正在分配给 $_map的别名有效。这是使用 $_ 的问题之一(或任何其他全局变量)——远距离的奇怪 Action 。如果您打算使用 $_ ,先本地化:
local $_;
while (<IN>)
...

或者,使用词法变量代替:
while (my $line = <IN>)

关于Perl 默认变量 $_,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3539086/

相关文章:

c++ - Linux 环境中用于 Perl 和 C++ 脚本的最佳且有用的调试工具是什么?

perl - Perl 中的 "Use of uninitialized value in scalar chomp"

使用只有 3 位索引的列表元素的正则表达式替换不能按我预期的那样工作

arrays - 使 perl 数组唯一

Perl 套接字发送散列

linux - Perl/Linux 用另一个文件的内容过滤大文件

c++ - 在 C++ 中使用 Perl + Regex 将#define 更改为#undef

perl - 如何检查客户端是否已断开连接?

Perl API 内联 C : How to get get a substr of a Perl byte string by reference without copying that string

用于后处理的 perl 代码结构