Realbot has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
as you can see in the following script, if I use the whole package name I can get an object method reference. Is it possible to achieve the same functionality with __PACKAGE__? Something like the commented line in foobar, which doesn't work...
Thanks!
package Very::Long::Name; sub new { my $self = {}; bless($self); return $self; } sub foo { return "hello\n"; } sub bar { my ($self, $subref) = @_; return $self->$subref(); } sub foobar { my $self = shift; return $self->bar(\&Very::Long::Name::foo); # return $self->bar(\&__PACKAGE__::foo); # this gives me error } package Main; my $obj = Very::Long::Name->new(); print $obj->foobar();

Replies are listed 'Best First'.
Re: __PACKAGE__ and method reference
by borisz (Canon) on Mar 09, 2005 at 13:36 UTC
    you can use
    return $self->bar(\&{__PACKAGE__ . '::foo' });
    but I think this does the same:
    return $self->bar(\&foo);
    Boris
      Both worked fine. I don't know why I thought that full package was needed...
      Thanks!
Re: __PACKAGE__ and method reference
by PodMaster (Abbot) on Mar 09, 2005 at 13:41 UTC
    \&{__PACKAGE__.'::foo'}

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Re: __PACKAGE__ and method reference
by chromatic (Archbishop) on Mar 09, 2005 at 17:25 UTC

    Do you want people to be able to subclass Very::Long::Name? In that case, hardcoding the subroutine reference won't allow them to override foo(). This will:

    return $self->bar( $self->can( 'foo' ) );

    (Also change to the two-arg form of bless if subclassability is important.)