微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在这个Perl子程序中使用vars的要点是什么?

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;
}

我不明白使用vars qw($a $b)行的含义是什么.即使我评论,我得到相同的输出和警告.

解决方法

这是因为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禁用再次运行它.

原文地址:https://www.jb51.cc/Perl/171531.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐