Scalar and List Context
Every operation[53] that you invoke in a Perl script is evaluated in a specific context, and how that operation behaves may depend on the requirements of that context. There are two major contexts: scalar and list. For example, assignment to a scalar variable, or to a scalar element of an array or hash, evaluates the righthand side in a scalar context:
$x = funkshun(); # scalar context
$x[1] = funkshun(); # scalar context
$x{"ray"} = funkshun(); # scalar contextBut assignment to an array or a hash, or to a slice of either, evaluates the righthand side in a list context, even if the slice picks out only one element:
@x = funkshun(); # list context
@x[1] = funkshun(); # list context
@x{"ray"} = funkshun(); # list context
%x = funkshun(); # list contextAssignment to a list of scalars also provides list context to the righthand side, even if there’s only one element in the list:
($x,$y,$z) = funkshun(); # list context ($x) = funkshun(); # list context
These rules do not change at all when you declare a variable
by modifying the term with my,
state, or our, so we have:
my $x = funkshun(); # scalar context my @x = funkshun(); # list context my %x = funkshun(); # list context my ($x) = funkshun(); # list context
You will be miserable until you learn the difference between
scalar and list context, because certain operators (such as our
mythical funkshun function above) know which context they are in, and they return a list in contexts wanting a list but a scalar value ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access