Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: questions about bless's second argument

by GrandFather (Saint)
on Nov 19, 2020 at 23:52 UTC ( [id://11123862]=note: print w/replies, xml ) Need Help??


in reply to questions about bless's second argument

See perlobj for the full story. The short version is that the second argument is the 'class' of the instance being created. If you aren't using inheritance then it's not very interesting. However consider:

use strict; use warnings; package PrintMe; sub AsStr { my ($self) = @_; return $self->{str}; }; sub new { my ($class, $str) = @_; return bless {str => $str}, $class; } package PrintMeToo; use base 'PrintMe'; sub AsStr { my ($self) = @_; return 'Me too: ' . $self->SUPER::AsStr(); }; package main; my $meToo = PrintMeToo->new('This string'); print $meToo->AsStr();

Prints:

Me too: This string

PrintMeToo is derived from PrintMe and inherits the constructor 'new' from PrintMe. Calling the constructor (my $meToo = PrintMeToo->new('This string');) gets the inherited PrintMe constructor called but creates a PrintMeToo instance.

Calling AsStr on the PrintMeToo instance gets the PrintMeToo version of AsStr, but that version calls up to the base class (PrintMe) to get the result from the base class AsStr to concatenate to the text provided by PrintMeToo's AsStr.

Bottom line is, always use the two parameter version of bless and always use the first parameter to the constructor sub to provide the class name.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11123862]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-03-28 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found