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.