SPUG: basic array question

Itay Furman itayf at u.washington.edu
Tue May 10 15:19:13 PDT 2005

I think the confusion arises from a (sublte?) differences between 
perl's concept of 'array' and 'list'.  Please see below my 
inserted comments.
Perhaps the gurus could add/correct my explanation.

On Tue, 10 May 2005, Mathew D. Watson wrote:

> #!/usr/bin/perl -w			# line 1
> @a = (@x = (1, 2, 3), $y = 'a', 9);	# line 2
LHS: array.  RHS: _list_.

> $a = (@x = (1, 2, 3), $y = 'a', 9);	# line 3
LHS: scalar.  RHS: _list_.

> $b = @a;				# line 4
LHS: scalar.  RHS: _array_

> @a on line 2 has the value (1, 2, 3, 'a', 9), which makes sense. The
> right hand side is evaluated in a list context because the variable on
> the left hand side is an array.

Wrong: right hand side is a _list_ which is _coerced_ into an 
array due to the LHS definition.

> $a on line 3 has the value 9, which is the last element of the array on
> the rhs. What is the rule at work here? Is the rhs considered an array?
> I'm not sure what context the rhs is evaluated in.

RHS is evaluated in a scalar context.  Since it is a _list_, each 
item in the (comma delimited list) is evaluated (by the comma 
operator ','), and then discarded, and evaluation proceeds to the 
next item.  Until the end of the list is hit.  Therefore, the 
last item is returned.
Please, read the documentation on the comma operator.

> $b on line 4 has the value 5, the number of elements in @a, which is
> what I thought might happen with $a on line 2. @a is evaluated in a
> scalar context because the lhs is a scalar. Why aren't $a and $b the same?

See above.

 	Hope this helps,

itayf at u.washington.edu  /  +1 (206) 543 9040  /  U of Washington

More information about the spug-list mailing list