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

I'm reading manuals and learning about context being imposed on variables.

In line 1 below, the parens around $a1 force a scalar context. The next line prints out 55 so the variable was assigned the FIRST value in the list. This makes sense because someone might write ($a1,@b) = (55,77,99) intending that the first value be assigned to $a1 and the remaining values go to @b as an array.

my ($a1) = (55,77,99); print $a1."\n";

So then I read that in the case of a hash, you force scalar by putting the keyword "scalar" in front of the list. So in the following example, I EXPECTED that $a2{'y'} would get the FIRST value in the list (as it did in the first example above) but it instead gets "9".

my %a2 = ( x=>4, y=> scalar (5,7,9) ); print $a2{'y'} . "\n";

Why would the assignment of a list in scalar context behave differently in these two scenarios?

Thanks for any help or links to an explanation.

Eric

Replies are listed 'Best First'.
Re: Newbie question - imposing context
by ikegami (Patriarch) on May 23, 2012 at 17:57 UTC

    Why would the assignment of a list in scalar context

    There's no list assignment in scalar context in your code. The assignment ("=") in each snippets is a list assignment evaluated in void context. "=>" is not an assignment, it's a fancy version of ",".

    You forced the list/comma operator to be evaluated in scalar context, and the list/comma operator in scalar context returns its last element. (Speaking loosely, see perlop for details.)

    In line 1 below, the parens around $a1 force a scalar context.

    It's the opposite. They force the selection of the list assignment operator, which in turn applies a *list* context to both its LHS and RHS operands. See Mini-Tutorial: Scalar vs List Assignment Operator.

Re: Newbie question - imposing context
by kcott (Archbishop) on May 23, 2012 at 18:06 UTC
    In line 1 below, the parens around $a1 force a scalar context.

    Actually, that's list context.

    What you're seeing here is how the comma operator behaves in list and scalar context. See perlop - Comma Operator for details.

    As a further example, compare scalar context (as in your example):

    $ perl -Mstrict -Mwarnings -E 'my %a2 = ( x=>4, y=> scalar (5,7,9) ); +say $a2{y}' Useless use of a constant (5) in void context at -e line 1. Useless use of a constant (7) in void context at -e line 1. 9

    with list context (removing scalar from your code):

    $ perl -Mstrict -Mwarnings -E 'my %a2 = ( x=>4, y=> (5,7,9) ); say $a2 +{y}' 5

    Update: Actually, a better example (for the list context) would be:

    $ perl -Mstrict -Mwarnings -E 'my %a2 = ( x=>4, y=> (5,7,9) ); say $a2 +{y}; say $a2{7}' 5 9

    -- Ken

      Thank you both for your help. I clearly have more than one misconception here. I need to re-read some stuff.