Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Your named arguments

by bageler (Hermit)
on Nov 08, 2005 at 18:32 UTC ( [id://506838]=note: print w/replies, xml ) Need Help??


in reply to Your named arguments

Here's the framework I use for new() subroutines for objects:
sub new { my ($class,%args) = @_; my $self = { %args }; bless $class, $self; $self->init(); }

Replies are listed 'Best First'.
Re^2: Your named arguments
by creamygoodness (Curate) on Nov 08, 2005 at 18:48 UTC
    Hi, I think you have a typo and an inefficiency in there. The bless line should be...

        bless $self, $class;

    ... or if you want objects to be able to spawn like objects...

        bless $self, ref($class) || $class;

    The ineffieciency comes from rolling the %args hash twice. It would be a little swifter if new looked like this instead...

    sub new { my $class = shift; my $self = { @_ }; bless $self, $class; $self->init(); }

    Lastly, the code counts on the init() sub returning $self, otherwise you'll get an error. That's an interesting choice. My version of init() doesn't, but it's only come up when trying to build a constructor that might return different object types based on the parameters. In that case, I had to override new(). I can see the merits of the alternative, though.

    --
    Marvin Humphrey
    Rectangular Research ― http://www.rectangular.com
      yes, that's what I meant :) That's what I get for posting after drinking.

Log In?
Username:
Password:

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

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

    No recent polls found