[Israel.pm] Confused about "my $class = ref($self) || $self;"

Offer Kaye offer.kaye at gmail.com
Wed Nov 2 00:57:10 PST 2005

Hi all,
I'm confused about the exact meaning and usage of the construct:
   my $class = ref($self) || $self;

The problem is that I found two references to such a construct in the
documention, however both are explained differently and both don't go
into depth exactly what it means to use this construct.

perlmodlib[1] has this to say:

or even this if you'd like it to be used as either a static or a virtual method.

 sub new {
     my $self  = shift;
     my $class = ref($self) || $self;
     return bless {}, $class;

That's it. A single sentence, no indication of when this would be
useful (examples of "new" being called with a reference and with a

perlobj[2] has this to say:

Or if you expect people to call not just CLASS->new()  but also
$obj->new() , then use something like the following...
    sub new {
	my $this = shift;
	my $class = ref($this) || $this;

This is only slightly better, as it gives 2 calling examples, but
leaves me in the dark as to when I would use the (to me) rather
strange "$obj->new()" and what it means to use such code.

As a further annoyance, the two POD pages use different variable names
for what is essentially the same example ($this vs. $self).

I'd like to understand exactly:
1. When should I use (or not use!) "my $class = ref($self) || $self;"?
Is it an inheritance related mechanism or something to aid in the
copying of objects (as perlobj seems to imply)?
2. 'new' usage examples that pass a reference and whose that simply
pass the class name.

Hopefully I will get a good enough answer that I will understand this
issue and be able to sumbit a patch to p5p for the above two PODs (I
hate broken docs)... :)

[1] http://perldoc.perl.org/perlmodlib.html
[2] http://perldoc.perl.org/perlobj.html

Thanks in advance,
Offer Kaye

More information about the Perl mailing list