本文介绍了在这个 Perl 子程序中使用 vars 有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 掌握 Perl 的一章中,brian d foy 展示了来自 List::Util:
In one of the chapters in Mastering Perl, brian d foy shows this snippet from 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;
}
我不明白 use vars qw($a $b)
行的意义何在.即使我评论它,我也会得到相同的输出 &警告.
I don't understand what's the point of the use vars qw($a $b)
line. Even if I comment it, I get the same output & warnings.
推荐答案
这样做是因为 List::Util 在内部使用了 reduce() 函数.
This is done because List::Util uses reduce() function internally.
在没有use vars
的情况下,使用该函数时给出如下警告:
In the abscence of use vars
, the following warning is given when the function is used:
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.
您可以通过运行以下代码亲眼看到这一点:
You can see this for yourself by running the following code:
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";
然后在禁用 use vars
的情况下再次运行它.
And then running it again with use vars
disabled.
这篇关于在这个 Perl 子程序中使用 vars 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!