Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: What means: "bless { @_ } => $class;"?

by Thelonius (Priest)
on Apr 24, 2006 at 00:48 UTC ( [id://545174]=note: print w/replies, xml ) Need Help??


in reply to What means: "bless { @_ } => $class;"?

Or does { @_ } create an annoymous hash from the elements of the argument array and if so, how does that => $class fit in?
The braces here create a reference to an anonymous hash. The curly braces are probably the most overloaded symbols in Perl. Sometimes the usage is even ambiguous and perl doesn't do what you would expect.

=> is essentially the same as a comma except that sometimes you don't need to quote what's on the left side of it (which isn't relevant here).

You could also write this as:

sub new { my $class = shift; my %self = @_; bless \%self, $class; }
or
sub new { my $class = shift; my $self = { @_ }; bless $self, $class; }

Replies are listed 'Best First'.
Re^2: What means: "bless { @_ } => $class;"?
by BerntB (Deacon) on Apr 24, 2006 at 02:13 UTC
    Better than I'd have answered. Just an addition, to be complete.

    The return value of the sub is the last eval:ed statement, in this case the 'bless'. It returns the reference (new object).

    It is a common idiom to place the bless last in 'new' methods, so the new object is returned.

    (The one asking the question probably knows this, since it says so in the Camel book about 'bless'. But just to be safe.. the other part of the question is almost there in the Camel book, too.)

    Update:
    Surprising, but if merlyn says it is a pedagogical problem, I'll believe it. :-) (That would be Perl-only programmers? The "return last value by default" is quite Perl-specific, afaik?)

      It is a common idiom to place the bless last in 'new' methods, so the new object is returned.
      The disadvantage of that is that you cannot call methods within the constructor to pick up class-related or instance-related initialization information.

      However, that's fairly rare for simple demonstrations. Hence, most people haven't seen the fact that more often in "real life", bless is done fairly early in the constructor, usually as soon as the hashref is constructed.

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

Log In?
Username:
Password:

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

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

    No recent polls found