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

    I'm sorry: I think I was very unclear in the original question, and simplified away the wrong bits. It's the package name of the factory that I want to capture in a method injected into the Drone class, so that the Drone (no idea why I called it that) can call instance() on the right factory class.

    The answer turns out to be very simple, and much the same as your neat constructions:

    sub post_require { my ($self, $class) = shift; my $factory_class=ref $self; no strict 'refs'; *{"$class::factory"} = sub { return $factory_class->instance; }; }

    but it does look like I can't do it without creating some kind of closure, which I was hoping to avoid...

    Thanks for your help.