Perl,使用哈希“封闭”

时间:2010-06-15 13:13:53

标签: perl closures

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

例如

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

my %obj = setup();
$obj{print_hello};

理想情况下,这会输出“hello world”

修改

抱歉,我没有指定一项要求

我应该能够做到

$obj{txt} = "goodbye";

然后$ obj {print_hello}应输出goodbye

3 个答案:

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

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

答案 1 :(得分:2)

这将有效:

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

my %obj = setup();
$obj{print_hello}->();

答案 2 :(得分:0)

关闭:

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

my %obj = setup();
$obj{print_hello}->();