O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required