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. If you’ve gotten away with skimming the text up to this point, this is where you should pay attention.

That’s not to say that this section is in difficult to understand. It’s a simple idea: a given expression may mean different things depending upon where it appears. This is nothing new; it happens all the time in natural languages. For example, in English,[77] suppose someone asked you what the word “read”[78] 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 a scalar or list value.[79] What Perl expects is called the context of the expression.[80]

    42 + something # The something must be a scalar
    sort something # The something must be a list

If something is the exact same sequence of characters, in one case it may give a single, scalar value, and in another, it may give a list.[81] Expressions in Perl always return the appropriate value for their context. For example, how about the “name”[82] of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements in the array:

 @people = qw( fred barney betty ...

Get Learning Perl, Fourth 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.