Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: why is a 2-argument bless not working in my situation

by Vautrin (Hermit)
on Mar 31, 2004 at 04:31 UTC ( [id://341197]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2024-04-25 11:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found