在这个Perl子程序中"使用vars"有什么意义?

Geo*_*Geo 10 perl

Mastering Perl的其中一章中,brian d foy从List :: Util中显示了这个片段:

sub reduce(&@) {
    my $code = shift;
    no strict "refs";
    return shift unless @_ > 1;
    use vars qw($a $b);
    my $caller = caller;
    local(*{$caller . "::a"}) = \my $a;
    local(*{$caller . "::b"}) = \my $b;
    $a = shift;
    foreach(@_) {
        $b = $_;
        $a = &{$code}();
    }
    $a;
}
Run Code Online (Sandbox Code Playgroud)

我不明白这条use vars qw($a $b)线的意义.即使我评论它,我得到相同的输出和警告.

DVK*_*DVK 11

这样做是因为List :: Util在内部使用reduce()函数.

use vars使用函数时,会给出以下警告:

Name "List::MyUtil::a" used only once: possible typo at a.pl line 35.
Name "List::MyUtil::b" used only once: possible typo at a.pl line 35.
Run Code Online (Sandbox Code Playgroud)

您可以通过运行以下代码自行查看:

use strict;
use warnings;

package List::MyUtil;

sub reduce (&@) {
   # INSERT THE TEXT FROM SUBROUTINE HERE - deleted to save space in the answer
}

sub x {
    return reduce(sub {$a+$b}, 1,2,3);
}

package main;
my $res = List::MyUtil::x();
print "$res\n";
Run Code Online (Sandbox Code Playgroud)

然后在use vars禁用的情况下再次运行它.

  • 正确答案的提示在于使用vars仅适用于当前包.因此,List :: Utils本身对任何人都没有用. (3认同)
  • 至于引用全局变量,我假设没有人应该使用全局变量 - 你不想踩到其他代码的脚. (3认同)