Scalar and List Context
This is the most important section in this chapter. In fact, it’s the most important section in the entire book. It wouldn’t be an exaggeration to say that your entire career in using Perl will depend upon understanding this section. So if you’ve gotten away with skimming the text up to this point, this is where you should really pay attention.
That’s not to say that this section is in any way difficult to understand. It’s actually a simple idea: a given expression may mean different things depending upon where it appears. This is nothing new to you; it happens all the time in natural languages. For example, in English,[*] suppose someone asked you what the word “read”[†] means. It has different meanings depending on how it’s used. You can’t identify the meaning until you know the context.
The context refers to where an expression is found. As Perl is parsing your expressions, it always expects either a scalar value or a list value.[*] What Perl expects is called the context of the expression.[†]
42 + something # The something must be a scalar sort something # The something must be a list
Even if something is the exact same sequence of characters, in one case it may give a single, scalar value, while in the other, it may give a list.[‡] Expressions in Perl always return the appropriate value for their context. For example, take the “name”[‖] of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements ...
Get Learning Perl, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.