package UsesClosures; sub new { my $attr; return bless({ get_attr => sub { $attr }, set_attr => sub { $attr = $_[1] }, some_method => sub { print "$attr\n"; } }, shift); } sub get_attr { &{ shift->{get_attr } } }; sub set_attr { &{ shift->{set_attr } } }; sub some_method { &{ shift->{some_method} } };
my $o = UsesClosures->new(); $o->set_attr(123); print $o->get_attr(); $o->some_method();
Your Dinner module would be:
package Dinner; sub new { my $hands_clean = 1; return bless({ wash_hands => sub { $hands_clean = 1; }, eat_food => sub { die "Filthy\n if !$hands_clean; print "Om nom nom\n"; }, }, shift); } sub wash_hands { &{ shift->{wash_hands} } }; sub eat_food { &{ shift->{eat_food } } };
my $dirtyeater = Dinner->new(); $dirtyeater->wash_hands(); $dirtyeater->eat_food();
Like inside-out objects, such objects are hard to debug.
In reply to Re: Using closures to achieve data hiding in OO Perl
by ikegami
in thread Using closures to achieve data hiding in OO Perl
by saurabh.hirani
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |