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

Shlomi Fish shlomif at iglu.org.il
Wed Nov 2 02:09:57 PST 2005


On Wednesday 02 November 2005 10:57, Offer Kaye wrote:
> 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:
>
> <blockquote>
> 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;
>  }
> </blockquote>
>
> 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
> string).
>
> perlobj[2] has this to say:
>
> <blockquote>
> 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;
> </blockquote>
>
> 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.

You'll use $obj->new() in case you want to create a new object with the same 
class as $obj.

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

It does not really aid in the copying of objects. For this you need a copy 
constructor of some sort. What it does aid is in the creation of a new object 
of the same class, as the object.

Regards,

	Shlomi Fish

> 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
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

-- 

---------------------------------------------------------------------
Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

95% of the programmers consider 95% of the code they did not write, in the
bottom 5%.



More information about the Perl mailing list