Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Return Value of List-Producing Elements in Scalar Context

by LanX (Saint)
on Jul 28, 2013 at 14:26 UTC ( [id://1046742]=note: print w/replies, xml ) Need Help??


in reply to Re: Return Value of List-Producing Elements in Scalar Context
in thread Return Value of List-Producing Elements in Scalar Context

> A "list producing expression used in scalar context" does not produce a list. It just produces a single value, which is the last element in the comma-delimited expression.

Maybe better phrased "a list-producing expression used in scalar context" will not produce an intermediate LIST which is then evaluated in scalar context, but a scalar is produced depending on the value.

DB<102> scalar (a..d) => "1E0" DB<103> sub tst {a..d} DB<104> tst() => ("a", "b", "c", "d") DB<105> scalar tst() => "1E0" DB<106> scalar ("a", "b", "c", "d") => "d" DB<107> sub tst { @{[a..d]} } DB<108> scalar tst() => 4

I wonder if a listify operator could help avoiding bugs when changing the return expression of a sub.

Cheers Rolf

( addicted to the Perl Programming Language)

Replies are listed 'Best First'.
Re^3: Return Value of List-Producing Elements in Scalar Context
by AnomalousMonk (Archbishop) on Jul 28, 2013 at 15:21 UTC
    I wonder if a listify operator could help avoiding bugs when changing the return expression of a sub.

    It might help (and indeed, I think Perl6 has the list operator — but don't quote me), but the context in which the  .. and  ... range/flip-flop operators act is usually pretty clear. scalar alone serves pretty well in this case and in general since it's very easy to induce list context, so easy that one almost gets the impression it's the default!

      I was already bitten by a case where I wanted to return a list like 1,2,3 from a sub and replaced it with  1..3 which acted differently in scalar context.

      True I should have used wantarray, but one intuitively expect a constant behavior...

      (I had different code-branches which returned and I didn't want to duplicate wantarray checks for each branch.)

      FWIW, here a possible implementation of listify: Re^3: wantarray alternative

      Maybe something like l_return (always return list) and a_return (always return array) could help...

      Cheers Rolf

      ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1046742]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-23 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found