package Dinner; use strict; use warnings; my $self = {}; sub new { my ($class) = @_; bless $self, $class; return $self; } sub washhands { my ($obj) = @_; $obj->{'handsclean'} = 1; return 1; } sub eatfood { my ($obj) = @_; if (exists $obj->{'handsclean'}) { print "\nYou washed your hands -eat all you want\n"; } else { print "\nYou filthy animal!! Go wash your hands\n"; } return 1; } 1; #### #!/usr/bin/perl -w use strict; use Dinner; my $dirtyeater = Dinner->new(); # I don't want to wash hands, I will just set the flag directly # $dirtyeater->washhands; $dirtyeater->{'handsclean'} = 1; $dirtyeater->eatfood; #### $VAR1 = bless( { 'handsclean' => 1 }, 'Dinner' ); #### package Dinnerclosure; use strict; use warnings; sub new { my ($class) = @_; my $self = {}; my $selfmirage = {}; $selfmirage->{'washhands'} = sub { washhands($self); }; $selfmirage->{'eatfood'} = sub { eatfood($self); }; bless $selfmirage, $class; return $selfmirage; } sub washhands { my ($obj) = @_; $obj->{'handsclean'} = 1; return 1; } sub eatfood { my ($obj) = @_; if (exists $obj->{'handsclean'}) { print "\nYou washed your hands -eat all you want\n"; } else { print "\nYou filthy animal!! Go wash your hands\n"; } return 1; } 1; #### #!/usr/bin/perl -w use strict; use Dinnerclosure; my $cleaneater = Dinnerclosure->new(); # comment next line and uncomment the one after it, but it won't wash hands $cleaneater->{'washhands'}->(); #$cleaneater->{'handsclean'} = 1; $cleaneater->{'eatfood'}->(); print Dumper $cleaneater; #### $VAR1 = bless( { 'eatfood' => sub { "DUMMY" }, 'washhands' => sub { "DUMMY" } }, 'Dinnerclosure' );