|Do you know where your variables are?|
Re: Confused as to why the "casting context" is mis-behaving ("list vs array", again)by tye (Cardinal)
|on Oct 21, 2010 at 05:24 UTC||Need Help??|
Ah, lots of constructing of the false dichotomy of "list" vs "array". "It returns/is a list and therefore returns its last item in scalar context" is utter nonsense, though quite persistent nonsense in part because it gives the "right answer" in several cases. Also because "list" is very often used to mean "list literal" (use of the comma operator) and is also very often used to talk about what is returned by lots of different things, including slices.
So, yes, a list literal gives its last item in scalar context (be careful how you define "item", though). Yes, a slice returns a list of scalar values. Yes, lots of things that return a list of scalar values also return the last item when in scalar context. Yes, slices do that.
But, no, a list of scalar values is not a list literal (a list literal does return a list of scalar values when used in a list context). No, a slice does not return a list literal; a list literal is a syntax construct and thus is not something that can be "returned". No, not all things that return a list of scalar values give the last item when in scalar context. No, a slice is not just syntactic sugar for a list literal.
And, no, the last time I checked, what a slice returns in scalar context is not even documented. Nor was it designed. It came to be as a quick patch to fix a core dump and no documentation change accompanied it.
Yes, grep and map both return lists of scalar values. Yes, they both return the number of elements when in a scalar context. By the logic of the "is it a list or an array?" meme, clearly grep and map must return arrays. No, they don't return arrays (for example, you can push to an array). You can't even return an array in Perl (you can return a reference to an array and you can write "return @array;" but that returns (a copy of) the list of scalar values that are in the array).
The reality is that each operation type in Perl that can return a list (of scalar values) also has a specific thing it will return when in a scalar context. Almost all of those cases are documented. The majority of cases return the last item. Several return a count. Several return the first item. Even more do something else.
Slices return the last item because that is the easiest thing to do in a quick patch (you just reduce the stack size to 1) and that quick patch got accepted. Period.
(Update) On Scalar Context lists many of the cases.