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

前端之家收集整理的这篇文章主要介绍了在这个Perl子程序中使用vars的要点是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Mastering Perl年的其中一个章节中,brian d foy从 List::Util开始显示这个代码段:
  1. sub reduce(&@) {
  2. my $code = shift;
  3. no strict "refs";
  4. return shift unless @_ > 1;
  5. use vars qw($a $b);
  6. my $caller = caller;
  7. local(*{$caller . "::a"}) = \my $a;
  8. local(*{$caller . "::b"}) = \my $b;
  9. $a = shift;
  10. foreach(@_) {
  11. $b = $_;
  12. $a = &{$code}();
  13. }
  14. $a;
  15. }

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

解决方法

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

在使用vars的时候,使用该函数时会给出以下警告:

  1. Name "List::MyUtil::a" used only once: possible typo at a.pl line 35.
  2. Name "List::MyUtil::b" used only once: possible typo at a.pl line 35.

您可以通过运行以下代码为自己看到这一点:

  1. use strict;
  2. use warnings;
  3.  
  4. package List::MyUtil;
  5.  
  6. sub reduce (&@) {
  7. # INSERT THE TEXT FROM SUBROUTINE HERE - deleted to save space in the answer
  8. }
  9.  
  10. sub x {
  11. return reduce(sub {$a+$b},1,2,3);
  12. }
  13.  
  14. package main;
  15. my $res = List::MyUtil::x();
  16. print "$res\n";

然后使用vars禁用再次运行它.

猜你在找的Perl相关文章