English 中文(简体)
使用哈希语的“封闭”
原标题:Perl, "closure" using Hash

作为能够接触其他散装成员的散装成员的成员,我谨有一位非例行成员。

例如

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

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

理想的做法是,这将产生“hello World”

http://www.ohchr.org。

我没有说明一项要求。

我应该能够这样做。

$obj{txt} = "goodbye";

之后,Bobj{print_hello}应当输出goodbye

最佳回答

如果你想要打电话的守则能够更改散列中的信息,那么你需要参考回来。 你要求:

use strict;
use warnings;

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

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

$h->{msg} =  goodbye ;
$h->{express_yourself}->();

然而,它产生了一种奇怪的趋同——基本上是一个包含一些内在行为的数据结构。 象/object到我看。 或许,你们应当研究一下O-O办法,来开展你们的项目。

问题回答

这项工作将:

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

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

近距离:

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

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




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签