in reply to Re^2: __PACKAGE__ in anonysub
in thread __PACKAGE__ in anonysub
If it's a method, you could use:
package Factory; sub fixup { no strict 'refs'; *Drone::bar = sub { my $self = shift; my $class = ref($self); return $class; }; } package main; Factory::fixup(); @Drone::Subclass::ISA = 'Drone'; my $drone1 = bless({}, 'Drone'); my $drone2 = bless({}, 'Drone::Subclass'); print($drone1->bar(), $/); # Prints Drone print($drone2->bar(), $/); # Prints Drone::Subclass
or you could also use closures:
package Factory; sub fixup { no strict 'refs'; my $pkg = 'Drone'; *{"${pkg}::bar"} = sub { return $pkg; }; } package main; Factory::fixup(); @Drone::Subclass::ISA = 'Drone'; my $drone1 = bless({}, 'Drone'); my $drone2 = bless({}, 'Drone::Subclass'); print($drone1->bar(), $/); # Prints Drone print($drone2->bar(), $/); # Prints Drone
Note the slightly different output. I don't know which you would prefer.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: __PACKAGE__ in anonysub
by thpfft (Chaplain) on Feb 19, 2005 at 21:05 UTC |