Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

__PACKAGE__ and method reference

by Realbot (Scribe)
on Mar 09, 2005 at 13:25 UTC ( #437890=perlquestion: print w/replies, xml ) Need Help??

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...
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);
      Both worked fine. I don't know why I thought that full package was needed...
Re: __PACKAGE__ and method reference
by PodMaster (Abbot) on Mar 09, 2005 at 13:41 UTC

    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.)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://437890]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2022-12-09 22:26 GMT
Find Nodes?
    Voting Booth?

    No recent polls found