Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package MasterableThing;
use Moose;
has 'something' => (is => 'rw', isa => 'Str');
has 'master' => (is => 'rw');
sub do_this_thing {
my $themaster = $_[0]->master;
my $theoriginal = $_[0];
$_[0] = $themaster if defined $themaster;
my $code = $_[1];
$code->(@_[2 .. -1]);
$_[0] = $theoriginal;
return 1;
}
package main;
use MasterableThing;
sub main {
my $master_thing = MasterableThing->new(
something => 'master thing something',
);
my $slave_thing = MasterableThing->new(
something => 'slave thing something',
master => $master_thing,
);
my $thing = $master_thing;
print "thing is master thing: " . $thing->something ."\n";
$thing->do_this_thing(sub { print "doing this thing with: " . $thing->something . "\n"; });
print "thing is now: " . $thing->something . " something\n";
print "\n";
$thing = $slave_thing;
print "thing is slave thing: " . $thing->something ."\n";
$thing->do_this_thing(sub { print "doing this thing with: " . $thing->something . "\n"; });
print "thing is now: " . $thing->something . " something\n";
}
main();
# results:
#
# thing is master thing: master thing something
# doing this thing with: master thing something
# thing is now: master thing something something
#
# thing is slave thing: slave thing something
# doing this thing with: master thing something
# thing is now: slave thing something something
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment