3.1.10 Coercion Between an Array and a Scalar
We have seen that when we write
$var = @list;
the scalar variable $var gets the length of the array. This is because the presence of a scalar on the left hand side of the assignment statement causes Perl to expect a scalar on the right hand side also. In such a scalar context, Perl returns a scalar, the number of elements in the array. However, there is a word of caution. Perl behaves differently if we do not have a single array variable such as @list on the right hand side. For example, if we write
$count = @friends98, @friends99;
the comma is not considered a list element separator, but the so-called comma operator. The comma operator causes Perl to evaluate the left operand @friends98, ignore the result of the evaluation, then evaluate the right hand operator @friends99, and return the result of the second evaluation as the value of the comma operation. @friends99 is evaluated in scalar context. Therefore, $count contains the length of the second list after the statement is executed. However, after executing
$count = (@friends98, @friends99);
$count has the length of the combined list.
On the other hand, it is also possible to write something like the following. Perl does not complain.
@list = $var;
In this case, on the left hand side of the assignment, we have an array. So, Perl expects an array on the right hand side also, but finds a scalar. Perl makes a list with $var as its only element and assigns this value to the list.
Such assignments, as the ones discussed above, work silently, without complaining, but it is not good programming practice. Unless one knows what one is doing, such assignments make the program difficult to debug and difficult to understand by others.
