在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
禁用的情况下再次运行它.
归档时间: |
|
查看次数: |
2462 次 |
最近记录: |