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!


In reply to Re: Re^5: What should be returned in scalar context? (missing?) by BrowserUk
in thread What should be returned in scalar context? by tilly

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.