Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Return Value of List-Producing Elements in Scalar Context

by pikus (Hermit)
on Aug 23, 2004 at 15:22 UTC ( [id://385100]=perlquestion: print w/replies, xml ) Need Help??

pikus has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks! I beseech thee for thine tender mercies and humbly request you end my misery. My dilemma is this:

I'm re-reading verious parts of Learning Perl in an effort to gain greater understanding. In Chapter 3: Lists and Arrays there is a section about Scalar and List Context. I grasp the concept of context, but is says, "Most list-producing expressions {used in scalar context} return something much more interesting than {the number of elements in the list}." What does this mean? I've looked and found no mention or example of anything other than the number of elements being returned by list-producing elements in scalar context. That doesn't mean it's not there I guess, but I can't find it.

Would someone mind shedding a little light on this for me?

Thank you all.
     - pikus
"I want to live 'till I die. No more. No less." - Eddie Izzard
  • Comment on Return Value of List-Producing Elements in Scalar Context

Replies are listed 'Best First'.
Re: Return Value of List-Producing Elements in Scalar Context
by davido (Cardinal) on Aug 23, 2004 at 15:31 UTC

    merlyn posted an excellent node summarizing this statement. In it, you'll find that caller, in scalar context returns the package name. One useful item is localtime, which in scalar context returns a well formatted timestamp, while in list context returns individual portions of the date and time split out into individual elements. glob in scalar context returns the next item (you can repeat until it returns undef).

    merlyn's list is here: On Scalar Context. It's very informative.


    Dave

Re: Return Value of List-Producing Elements in Scalar Context
by rsteinke (Scribe) on Aug 23, 2004 at 15:33 UTC

    What this is (I believe) refering to is the fact that a function that returns a list in list context can return any scalar it wants in scalar context. Using the 'wantarray' builtin, a function could return:

    sub my_func { ... return @list_return if wantarray; return $scalar_return; }
    The scalar return value could be the number of elements in the list, but it could also be just about anything else. In sensibly written functions, the scalar and list return values should either be related to each other, or related to side effects of the function. Choosing the most sensible thing to return in each case is an exercise in design.

    To find specific cases, you'd have to look at specific functions. Try the function reference at the end of Programming Perl for examples.

    Ron Steinke
    <rsteinke@w-link.net>
Re: Return Value of List-Producing Elements in Scalar Context
by ccn (Vicar) on Aug 23, 2004 at 15:25 UTC
Re: Return Value of List-Producing Elements in Scalar Context
by ikegami (Patriarch) on Aug 23, 2004 at 15:32 UTC

    Normally, $a = @array; will store the number of elements in the list in $a. That is not always the case, because of wantarray. For example:

    $scalar = localtime(); print($scalar, "\n"); # "Mon Aug 23 11:31:16 2004" @array = localtime(); $scalar = @array; print($scalar, ':', join(',', @array), "\n"); # 9:16,31,11,23,7,104,1,235,1 @array = scalar(localtime()); $scalar = @array; print($scalar, ':', join(',', @array), "\n"); # 1:Mon Aug 23 11:34:30 2004

    Update: Fixed error pointed out by davorg

      Normally, $a = ( ...list... ); will store the number of elements in the list in $a.

      Did you test that before you wrote it?

      $ perl -le '$a = (3, 4, 5); print $a' 5

      I think you're confusing lists and arrays.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        I did test it, but the last element of the list was the number of elements in the list... Fixed my original post.

Re: Return Value of List-Producing Elements in Scalar Context
by pikus (Hermit) on Aug 23, 2004 at 20:12 UTC
    Awesome! Thanks to all of you. I can't believe the responses came so quickly! 3 minutes. Is that some kind of record? :)
         - pikus
    "I want to live 'till I die. No more. No less." - Eddie Izzard
Re: Return Value of List-Producing Elements in Scalar Context
by radiantmatrix (Parson) on Aug 24, 2004 at 14:32 UTC
    humbly request you end my misery
    Try this:
    # @users is an array of hashes. for (@users) { if ($_{clue} <= 0) { kill($_); } else { print STDERR "User with clue found: your data may be invalid"; } }
    :P
    --
    $me = rand($hacker{perl});
Re: Return Value of List-Producing Elements in Scalar Context
by davido (Cardinal) on Jul 28, 2013 at 03:48 UTC

    The important thing to understand (and something that I clearly misunderstood ten years ago -- I still remember the feeling of egg on face) is that there simply is no such thing as a list 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. (That's as near as I can come to describing the right-hand-side.)

    So the truth is that this construct:

    my $a = ( 10, 20, 30, 40, 50 );

    ...is not generating a list in scalar context and then assigning the last element to $a. It's assigning the scalar value 50 to $a, that's it. There's no list, and the entity has a size of one.

    B::Deparse's output is interesting when list-producing syntax is used in scalar context. There's no list. :)

    perl -MO=Deparse -E '$x = (10,20,30); say $x'

    There you'll see the comma operator at work doing what it's supposed to do in scalar context: throwing away the item on the lefthand, returning the one on the right.


    Dave

      > 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)

        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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://385100]
Approved by Old_Gray_Bear
Front-paged by Elijah
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2024-04-25 04:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found