What am I missing?
Note that the node title mentions "scalar context". This is what you are missing. Compare your two foo()s when called in a scalar context.
| [reply] |
Right tye, ysth pointed this out to me by /msg also.
If the original version is called in a scalar context when returning the list 'foo', 'bar', 'baz', the result is 'baz'.
My version returns 3.
Now the question is why?
Why preserve or emulate the list-in-a-scalar-context semantics?
Is there ever a situation when arbitrarially returning the last physical value in a list is the right thing to do?
And if anyone knows of such an occasion, does this occur so frequently that it is worth while imposing the additional costs on every other use of the sub in order to avoid the need to do
my $last = ( foo() )[ -1 ];
which would be hugely clearer as to the desired result than my $last = foo(); as well as considerably more efficient for the general case.
I've always considered this side-effect of a list in a scalar context to be terminally broken and something that really ought to be fixed. The argument against fixing it is probably backwards compatibility, but I would argue that given the rarity that this behaviour is likely to be used and depended upon by real code, and that it is so easy to achieve the equivalent with a simple modification that increases the clarity of the desired result so much, that it would be better for everyone to force the fix upon existing code that relies upon this behaviour.
I find the idea of coding a sub in such a convoluted manner in order to perpetuate this broken behaviour an anathema.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!
Wanted!
| [reply] [d/l] [select] |