3.4.3 The Context--List vs. Scalar
It may have occurred to you by now that in certain places we can use a
list, and in other places we can use a scalar. Perl knows this as well,
and decides which is permitted by something called a context.
The context can be either list context or scalar context. Many operations
do different things depending on what the current context is.
For example, it is actually valid to use an array variable, such as
@array
, in a scalar context. When you do this, the array variable
evaluates to the number of elements in the array. Consider this example:
use strict;
my @things = qw/a few of my favorite/;
my $count = @things; # $count is 5
my @moreThings = @things; # @moreThings is same as @things
Note that Perl knows not to try and stuff @things
into a scalar,
which does not make any sense. It evaluates @things
in a scalar
context and given the number of elements in the array.
You must always be aware of the context of your operations. Assuming the
wrong context can cause a plethora of problems for the new Perl programmer.