在
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;
- }
解决方法
这是因为List :: Util在内部使用reduce()函数.
在使用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.
您可以通过运行以下代码为自己看到这一点:
- 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";
然后使用vars禁用再次运行它.