|Perl: the Markov chain saw|
Arrays are not listsby tilly (Archbishop)
|on Aug 05, 2000 at 09:52 UTC||Need Help??|
This meditation attempts to clarify a fundamental point that many monks have been led astray on. Compare the following two functions:
(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.