Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
The arrow operator always operates on the value to its left. That means that your second example would be equivalent to this:
my $result1 = $Person->name('Homer'); my $result2 = $result1->job('safety inspector'); my $result3 = $result2->wife('Marge'); $result3->fav_food('Duff');
where the result variables are temporary. In order for the code to work as expected, the methods (name, job, wife, fav_food) must return the original object. A sample method that works this way would look like this (assuming the object is a hash ref):
sub name { my ($self, $value) = @_; if (defined $value) { # if a value is given $self->{name} = $value; # set the value return $self; # return the original object } return $self->{name}; # else return the name }
This code fragment will set the value and return the object if a value is given, else it will return what the name is set as.

So why do you sometimes see the original object ($Person in this case) have multiple method calls originating from the original obect on multiple lines? Because if the method returns a value other than itself (which is quite common), it will try to call the method on that value, and most likely fail.

elusion : http://matt.diephouse.com


In reply to Re: Getting Confused with the '->' operator by elusion
in thread Getting Confused with the '->' operator by the_Don

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-03-28 18:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found