On Tue, Sep 16, 2014 at 12:12:05PM -0500, Andy Bach wrote:

>                                                    The other thing to think
> about is "context" - the LHS of the assigning "=" determines how the RHS
> list is treated.

So far, so good.  Well, almost ...

>                  In scalar context
> my $one_var = (1, 2, 3);
> 
> the list returns its element count

But, I'm afraid, this is a common misconception.  The fact is that there
is no such thing as a list in scalar context.

So what, then, is the construct above?

You were correct in saying that it (whatever it is) is evaluated in
scalar context.  In scalar context, the parentheses () are used simply
for precedence.  The commas are operators.

The comma operator evaluates its LHS, throws it away, evaluates its RHS
and returns that.  The comma operator is left associative (see perlop).

So the result of evaluating the RHS (1, 2, 3) is:

  (1, 2, 3) -> ((1, 2), 3) -> (2, 3) -> 3

And this is why $one_var gets the value 3 - not because there are three
elements in a list on the RHS.

This all becomes easier to understand if you don't use the values 1, 2
and 3 :)

See also perldoc -q 'difference between a list and an array'

-- 
Paul Johnson - p...@pjcj.net
http://www.pjcj.net

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to