|Perl Language Reference Manual|
by Larry Wall and others
Paperback (6"x9"), 724 pages
RRP £29.95 ($39.95)
Sales of this book support The Perl Foundation! Get a printed copy>>>
The interpretation of operations and values in Perl sometimes depends on the requirements of the context around the operation or value. There are two major contexts: list and scalar. Certain operations return list values in contexts wanting a list, and scalar values otherwise. If this is true of an operation it will be mentioned in the documentation for that operation. In other words, Perl overloads certain operations based on whether the expected return value is singular or plural. Some words in English work this way, like "fish" and "sheep".
In a reciprocal fashion, an operation provides either a scalar or a list context to each of its arguments. For example, if you say
int( <STDIN> )
the integer operation provides scalar context for the <> operator, which responds by reading one line from STDIN and passing it back to the integer operation, which will then find the integer value of that line and return that. If, on the other hand, you say
sort( <STDIN> )
then the sort operation provides list context for <>, which will proceed to read every line available up to the end of file, and pass that list of lines back to the sort routine, which will then sort those lines and return them as a list to whatever the context of the sort was.
Assignment is a little bit special in that it uses its left argument to determine the context for the right argument. Assignment to a scalar evaluates the right-hand side in scalar context, while assignment to an array or hash evaluates the righthand side in list context. Assignment to a list (or slice, which is just a list anyway) also evaluates the righthand side in list context.
When you use the
use warnings pragma or Perl's -w command-line
option, you may see warnings
about useless uses of constants or functions in "void context".
Void context just means the value has been discarded, such as a
statement containing only
getpwuid(0);. It still
counts as scalar context for functions that care whether or not
they're being called in list context.
User-defined subroutines may choose to care whether they are being called in a void, scalar, or list context. Most subroutines do not need to bother, though. That's because both scalars and lists are automatically interpolated into lists. See for how you would dynamically discern your function's calling context.
|ISBN 9781906966027||Perl Language Reference Manual||See the print edition|