Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Calling module function from within a blessed module

by tobyink (Canon)
on Jan 03, 2021 at 11:48 UTC ( [id://11126192]=note: print w/replies, xml ) Need Help??


in reply to Calling module function from within a blessed module

You are using the one argument version of bless.

sub new { return bless {}; }

Never, ever, ever do this. The one argument version of bless really should issue a warning.

Do this:

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

Replies are listed 'Best First'.
Re^2: Calling module function from within a blessed module
by Bod (Parson) on Jan 03, 2021 at 11:57 UTC
    Never, ever, ever do this. The one argument version of bless really should issue a warning.

    Actually, in real code I do not generally use the one argument version. I created that as a minimal example to support the question.

    Having said that, I don't know why I avoid the single argument version. It is because I have copied other code that works and looks like the author knows what they are doing which is not exactly the most rigorous methodology for learning...

      The reason why you generally shouldn't use the one-argument version of bless is because it makes subclassing more difficult.

      If you have two classes, Parent and Child, and Parent uses bless {}, $_[0];, then Child can simply inherit Parent's new (or other constructor) and Child->new() will Just WorkTM.

      If Parent uses one-argument bless, then it will always create a Parent object, and Child will have to override the constructor (either writing a completely new constructor, or calling Parent's constructor and re-blessing the result before returning it).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-03-29 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found