
waltz
Novice
Jun 14, 2011, 3:58 AM
Post #8 of 13
(1821 views)
|
|
Re: [waltz] closure - set hash key value
[In reply to]
|
Can't Post
|
|
Hello, see code bellow:
package Test; sub new { my $this = {}; my $pkg = shift; # constructor %{$this} = @_ if (scalar(@_) > 0); bless sub { if (scalar(@_) > 1) { # setters.. $this->{$_[0]} = $_[1]; } else { # getters.. return $this->{$_[0]}; } }, $pkg; } sub get { my $this = shift; return &{$this}($_[0]); } sub set { my $this = shift; return &{$this}($_[0], $_[1]); } 1; package Main; my $a = Test->new('a', 'a set', 'aa', 'aa set'); my $b = Test->new('b', 'b set', 'bb', 'bb set'); print "res a\t" . $a->get('a') . "\n"; print "res b\t" . $b->get('b') . "\n"; $a->set('a', 'a2 test'); $b->set('b', 'b2 test'); # after.. print "res a\t" . $a->get('a') . "\n"; print "res b\t" . $b->get('b'); ..and look on this page: http://www.perlmonks.org/?node_id=8251 R.
|