http://www.perlmonks.org?node_id=341197


in reply to why is a 2-argument bless not working in my situation

All subroutines (or functions or methods or whatever you were taught to call them in CS101) in perl return a value. You can explicitely return a value by using a return statement, or, the last line is returned. For instance, in the function:

use strict; use warnings; sub foo { 1; } print foo, "\n";

You would see an output of 1. Now, you never explicitely returned a value of 1, but because it was the last thing on the line, Perl tried to do what you meant by returning 1. However, Perl is not psychic. So, when you see most constructors ending with:

bless $self, $class;

$self is not modified. An object is created when bless is evaluated. The following would do the same thing:

my $object = bless $self, $class; return $object;

Consult perldoc bless for more information. So, this:

bless ($self,$class); return $self;

should read:

return bless ($self, $class);

Also, note that the first element of @_ is the class name, not the second. So:

my ($self,$class)=@_;

Should really be the other way around, i.e.:

my ($class, $self) = @_; # and add a check that we're not copying # for good measure die ("This isn't a copy constructor") if (ref $class);

And unless you know what you're doing, you shouldn't use anything but a hashref for $self. I think you might want to google for @ISA and read up a little bit on inheritance.


Want to support the EFF and FSF by buying cool stuff? Click here.

Replies are listed 'Best First'.
Re: Re: why is a 2-argument bless not working in my situation
by Hofmator (Curate) on Mar 31, 2004 at 09:00 UTC
    However, Perl is not psychic. So, when you see most constructors ending with:   bless $self, $class; $self is not modified.
    This is wrong, $self is modified. Try e.g. this:
    sub foo { my $self = {}; bless $self, 'Bar'; return $self; } print "isa Bar.\n" if foo()->isa('Bar');

    -- Hofmator