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

In my quest for more Perl wisdom, I've come across the following tidbit. (Ignoring the lack of strict and -w in some code, this is the stripped down version).
package bar; # base class. Has a description method and an id method sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; $self->{DESCRIPTION} = "Bar!!!"; bless($self,$class); return $self; } sub description { my $self = shift; return $self->{DESCRIPTION}; } # return a description sub id { return __PACKAGE__; } # return the package name package foo; # inheriting from bar package, not overriding the id method. @ISA = qw(bar); use bar; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new; $self->{DESCRIPTION} = "Foo!!"; # yes I'm lazy :) bless($self,$class); return $self; } package main; use foo; $foo = new foo; print "Description is ",$foo->description,"\n"; print "Package is ",$foo->id,"\n";
So I have 2 packages, foo inherits from bar. In the bar package, I have a method using __PACKAGE__ to get the package name. I instanciate a foo object and call 2 available methods. Description returns the foo description, the id method returns the package name from bar.

Should I override id in the foo package too in order to getting __PACKAGE__ right?

Greetz
Beatnik
... Quidquid perl dictum sit, altum viditur.

Replies are listed 'Best First'.
Re: __PACKAGE__ interpolated before inheritence
by wog (Curate) on Dec 08, 2001 at 19:22 UTC

    If you want the id method to always return the package the object is blessed to you could just use ref:

    sub id { ref $_[0] }
      Not always but close enough :) I'm confused why __PACKAGE__ wont work.

      Greetz
      Beatnik
      ... Quidquid perl dictum sit, altum viditur.
        __PACKAGE__ is turned into, at compile time, the current package when it is compiled. (That is, the one established by package statements.)