in reply to Re: $self->{foo} in sub new {}
in thread $self->{foo} in sub new {}

This is a request for further enlightenment.

Since bless returns the blessed object, is there anything actually wrong with blessing the anonymous hash and assigning the result to $self?

In fact, in your example, it appears that $self could be done away with entirely:

sub new { my ($class, $foo) = @_; bless { foo => $foo } , $class; }
I understand that if new gets more involved and does more stuff with the object being created, that it would be a good thing to have a variable to work with. But it seems that the variable could be created and blessed first, then stocked with goods, and then returned, and I don't see any harm in it, though it isn't the way things are usually done.
sub new { my ($class, @args) = @_; my $self = bless {}, $class; # Do stuff with @args # ... # then return: $self; }
Where's the line between convention and Cargo Cult? This hints at being a meditation, except I don't really have the answers.

The PerlMonk tr/// Advocate

Replies are listed 'Best First'.
•Re: Re: Re: $self->{foo} in sub new {}
by merlyn (Sage) on Dec 22, 2003 at 21:10 UTC
    I think in one posting I mentioned an even shorter constructor:
    sub new { bless {}, shift }
    But we're not golfing here.

    I see no problem in letting the return value of bless be the return value from a constructor, provided that there's no need to address the intermediate reference during the construction of the object.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.