Perl,使用哈希"封闭"

Mik*_*ike 3 perl closures

我希望有一个子例程作为哈希的成员,该哈希能够访问其他哈希成员.

例如

sub setup {
  %a = (
   txt => "hello world",
   print_hello => sub {
    print ${txt};
  })
return %a
}

my %obj = setup();
$obj{print_hello};
Run Code Online (Sandbox Code Playgroud)

理想情况下,这将输出"你好世界"

编辑

对不起,我没有指定一个要求

我应该可以做到

$obj{txt} = "goodbye";
Run Code Online (Sandbox Code Playgroud)

然后输出$ obj {print_hello} goodbye

FMc*_*FMc 7

如果您希望调用代码能够修改散列中的消息,则需要通过引用返回散列.这符合您的要求:

use strict;
use warnings;

sub self_expressing_hash {
    my %h;
    %h = (
        msg              => "hello",
        express_yourself => sub { print $h{msg}, "\n" },
    );
    return \%h;
}

my $h = self_expressing_hash();
$h->{express_yourself}->();

$h->{msg} = 'goodbye';
$h->{express_yourself}->();
Run Code Online (Sandbox Code Playgroud)

然而,这是一个奇怪的混合 - 实质上是一个包含一些内置行为的数据结构.对我来说听起来像个对象.也许您应该为您的项目研究OO方法.