【问题标题】:How to execute lambda within a "closure scope"?如何在“闭包范围”内执行 lambda?
【发布时间】:2014-07-15 08:36:38
【问题描述】:

这是如何工作的?

    use strict;
    use warnings;

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

    base(sub {print $constant});

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

  1. 将 $constant 作为参数传递给驱动程序&$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});
    }
    

【问题讨论】:

  • 它不起作用。它将因“全局符号“$constant”需要显式包名称而死去
  • 对,那怎么处理呢?
  • 您到底想完成什么?为什么不将$constant 作为参数传入?
  • 因为我有很多 $constants(状态)和驱动程序(访问者)应该能够在不通过 args 传递所有内容的情况下启动并完成工作。
  • @name,所以只需传递一个包含所有内容的 hashref。

标签: perl lambda closures dynamic-scope


【解决方案1】:

这就是函数参数的用途。

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

【讨论】:

  • 除了1,2,3还有哪些选择?
  • 谢谢你,我以前没见过。那就是说我希望有类似于 c++x11 的东西。
猜你喜欢
  • 2013-12-07
  • 1970-01-01
  • 2015-09-04
  • 2012-11-03
  • 2014-05-22
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多