< BACKCONTINUE >

B.16 Scalar and List Context

Every operation in Perl is evaluated in either scalar or list context. Many operators behave differently depending on the context they are in, returning a list in list context and a scalar in scalar context.

The simplest example of scalar and list contexts is the assignment statement. If the left side (the variable being assigned a value) is a scalar variable, the right side (the values being assigned) are evaluated in scalar context. In the following examples, the right side is an array @array of two elements. When the left side is a scalar variable, it causes @array to be evaluated in scalar context. In scalar context, an array returns the number of elements in an array:

@array = ('one', 'two');
$a = @array;
print $a;

This prints:

2

If you put parentheses around the $a, you make it a list with one element, which causes @array to be evaluated in list context:

@array = ('one', 'two');
($a) = @array;
print $a;

This prints:

one

Notice that when assigning to a list, if there are not enough variables for all the values, the extra values are simply discarded. To capture all the variables, you'd do this:

@array = ('one', 'two');
($a, $b) = @array;
print "$a $b";

This prints:

one two

Similarly, if you have too many variables on the left for the number of right variables, the extra variables are assigned the undefined value undef.

When reading about Perl functions and operations, notice what the documentation has to say about scalar and list context. Very often, if your program is behaving strangely, it's because it is evaluating in a different context than you had thought.

Here are some general guidelines on when to expect scalar or list context:

  • You get list context from function calls (anything in the argument position is evaluated in list context) and from list assignments.

  • You get scalar context from string and number operators (arguments to such operators as . and + are assumed to be scalars); from boolean tests such as the conditional of an if () statement or the arguments to the || logical operator; and from scalar assignment.

< BACKCONTINUE >

Index terms contained in this section

assignment
      scalar and list context
context
list context
operators
      context and
Perl
      scalar and list context
scalar context
undefined values

© 2002, O'Reilly & Associates, Inc.