next up previous contents
Next: Creating Arrays Up: Arrays and Lists Previous: The Basics   Contents


Using a List in a Scalar Context

Perl tries to be flexible about handling different combinations of data in different situations, so it's important to understand what happens when you use one type of data in a situation where another type of data is really what is expected. When you use a list in a scalar context, perl's general rule is to use the number of elements of the array as the array's scalar value. Thus, to determine the number of elements in an array, it suffices to simply set the array equal to a scalar variable; that scalar variable will contain the number of elements in the array. In the following example, $l will be set to 5, since there are 5 elements in the @test array:
     @test = (7,3,13,9,1);
     $l = @test;
To force the conversion to scalar context, the scalar function can be used.

It should be mentioned that the standard arithmetic operators described in Section 3.3 all operate in scalar mode. That means whenever you use an array in an expression involving scalar arithmetic operators such as addition (+) or multiplication (*), the array will be used in scalar context, and the result will be a scalar, not an array. For example, consider the following statements:

     @nums = 1..10;
     @more = @nums + 3;
Since there are 10 elements in the @nums array, the array @more will contain just one element, the scalar value 13. In order to modify each element of an array in perl, it is necessary to use a loop or a function designed for that purpose, as described in the following sections and Section [*].


next up previous contents
Next: Creating Arrays Up: Arrays and Lists Previous: The Basics   Contents
Phil Spector 2002-10-18