Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
This meditation attempts to clarify a fundamental point that many monks have been led astray on. Compare the following two functions:
sub ret_array { return @_; } sub ret_list { return @_[0..$#_]; }
(EDIT: Alkabo pointed out why you shouldn't post code past midnight without re-reading and testing it. I just fixed an obvious typo in ret_list.)

Don't they look similar? Both just return what they were passed, don't they?

But look again. They differ in one significant particular. ret_list returns a list of things. ret_array an array.

But isn't an array a list?

As merlyn put it to me once, a list is a list of things and an array is a bag that contains a list. Now all things in Perl obey a context, which is scalar or list. In list context a list gives you itself. In scalar context it gives the last element. In list context an array gives you the list in the bag. In scalar context it gives you an envelope from the bag, the label saying how many things are in it.

These are seldom the same, and many is the time that a function which was supposed to return a list of words would return a 1 to me unexpectedly when I expected one word.

The moral is this. Think carefully when you write a function that returns a list of things. Some day it will be called in scalar context. Think about what you want it to do when that hapens, then test wantarray() before your return.

In reply to Arrays are not lists by tilly

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?

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-20 11:00 GMT
Find Nodes?
    Voting Booth?

    No recent polls found