List Processing
Much earlier in this chapter, we mentioned that Perl has two main contexts: scalar context (for dealing with singular things) and list context (for dealing with plural things). Many of the traditional operators we’ve described so far have been strictly scalar in their operation. They always take singular arguments (or pairs of singular arguments for binary operators) and always produce a singular result, even in list context. So if you write this:
@array = (1 + 2, 3 – 4, 5 * 6, 7 / 8);
you know that the list on the right side contains exactly four values, because the ordinary math operators always produce scalar values, even in the list context provided by the assignment to an array.
However, other Perl operators can produce either a scalar or a list value, depending on their context. They just “know” whether a scalar or a list is expected of them. But how will you know that? It turns out to be pretty easy to figure out, once you get your mind around a few key concepts.
First, list context has to be provided by something in the
“surroundings”. In the previous example, the list assignment provides it.
Earlier we saw that the list of a foreach loop provides it. The print operator also provides it. But you don’t
have to learn these one by one.
If you look at the various syntax summaries scattered throughout the
rest of the book, you’ll see various operators that are defined to take a
LIST as an argument. Those are the operators
that provide list context. Throughout this ...
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