1

这怎么行?

    use strict;
    use warnings;

    sub base {
      my $constant = "abcd";
      my ($driver_cr) = (@_);
      &$driver_cr;
    }

    base(sub {print $constant});

换句话说,$driver_cr 如何在没有以下条件的情况下访问 $constant:

  1. 将 $constant 作为 arg 传递给驱动程序 &$driver_cr($constant)
  2. 将 $constant 的范围更改为全局our $constant = "abcd";
  3. 制作一个公共块并从基础移动 $constant:

    use strict;
    use warnings;
    
    {
      my $constant = "abcd";
      sub base {
        my ($driver_cr) = (@_);
        &$driver_cr;
      }
      base(sub {print $constant});
    }
    
4

1 回答 1

4

这就是函数参数的用途。

use strict;
use warnings;

sub base {
  my $constant = "abcd";
  my ($driver_cr) = (@_);
  $driver_cr->($constant);
}

base(sub {
    my $constant = shift;
    print $constant;
});

但如果你真的反对传递参数,那么:

use strict;
use warnings;
use Acme::Lexical::Thief;

sub base {
  my $constant = "abcd";
  my ($driver_cr) = (@_);
  &$driver_cr;
}

base(sub {
    steal $constant;
    print $constant;
});
于 2014-07-15T08:46:35.017 回答