nysus has asked for the wisdom of the Perl Monks concerning the following question:
I want a Moose object to behave differently depending upon which package has created the object. For example, if the "Teacher" package create the "Child" object, I want the "Child" object to behave different than if the "Parent" object created the "Child" object.
To accomplish this, I have something like the following code:
1 #! /usr/bin/env perl 2 use strict; 3 use warnings; 4 5 package Child; 6 use Moose; 7 8 has 'context' => (is => 'rw'); 9 10 sub BUILD { 11 my $s = shift; 12 my ($pkg) = caller 4; 13 $s->context('Teacher') if $pkg eq 'Teacher'; 14 $s->context('Parent') if $pkg eq 'Parent'; 15 } 16 17 package Teacher; 18 my $tom = Child->new(); 19 print $tom->context . "\n"; 20 21 package Parent; 22 my $kit = Child->new(); 23 print $kit->context . "\n";
This works, but it is dependent upon line 12 guessing that the original caller being 4 (5?) levels deep.If Moose internals change at all, the code will break. So I'm wondering if there might be a more reliable and documented way of accomplishing this. Or perhaps it's best to pass in the "context" as an argument to the constructor (though this seems like a less cool approach)? It also seems like this approach could have a proper name in computer science but I'm not aware of. If you can educate me, I'd appreciate it. Thanks!
$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: What is a reliable way to get the package of the code creating a Moose object?
by choroba (Cardinal) on Jul 12, 2018 at 07:06 UTC | |
by nysus (Parson) on Jul 12, 2018 at 13:32 UTC | |
by Corion (Patriarch) on Jul 12, 2018 at 13:39 UTC | |
by nysus (Parson) on Jul 12, 2018 at 14:21 UTC | |
by choroba (Cardinal) on Jul 12, 2018 at 13:35 UTC | |
Re: What is a reliable way to get the package of the code creating a Moose object?
by anonymized user 468275 (Curate) on Jul 13, 2018 at 10:38 UTC | |
by tobyink (Canon) on Jul 15, 2018 at 08:23 UTC |