如何在"闭包范围内执行lambda"?

时间:2014-07-15 08:36:39

标签: perl lambda closures dynamic-scope

这如何运作?

    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. 制作一个公共块并从base移动$ constant:

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

1 个答案:

答案 0 :(得分: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;
});