In spoken languages, the meaning of a word or phrase may depend on how you use it; the local context helps clarify the intent. For example, the inappropriate pluralization of "Please give me one hamburgers!"The pluralization of the noun differs from the amount. sounds wrong, just as the incorrect gender of "la gato"The article is feminine, but the noun is masculine. makes native speakers chuckle. Consider also the pronoun "you" or the noun "sheep" which can be singular or plural depending on context.
Context in Perl is similar. It governs the amount as well as the kind of data to use. Perl will happily attempt to provide exactly what you ask for--provided you do so by choosing the appropriate context.
Certain Perl operations produce different behaviors when you want zero, one, or many results. A specific construct in Perl may do something different if you write "Do this, but I don't care about any results" compared to "Do this, and I expect multiple results." Other operations allow you to specify whether you expect to work with numeric data, textual data, or true or false data.
Context can be tricky if you try to write or read Perl code as a series of single expressions extracted from their environments. You may find yourself slapping your forehead after a long debugging session when you discover that your assumptions about context were incorrect. If instead you're cognizant of context, your code will be more correct--and cleaner, flexible, and more concise.
Amount context context governs how many items you expect from an operation. The English language's subject-verb number agreement is a close parallel. Even without knowing the formal description of this linguistic principle, you probably understand the error in the sentence "Perl are a fun language". In Perl, the number of items you request determines how many you get.
Suppose you have a function (functions) called find_chores()
which sorts your household todo list in order of task priority. The means by which you call this function determines what it will produce. You may have no time to do chores, in which case calling the function is an attempt to look industrious. You may have enough time to do one task, or you could have a burst of energy on a free weekend and desire to accomplish as much as possible.
If you call the function on its own and never use its return value, you've called the function in void context:
Assigning the function's return value to a single item (scalars) evaluates the function in scalar context:
Assigning the results of calling the function to an array (arrays) or a list, or using it in a list, evaluates the function in list context:
The parentheses in the second line of the previous example group the two variable declarations (lexical_scope) so that assignment will behave as you expect. If @rest
were to go unused, you could also correctly write:
.... in which case the parentheses give a hint to the Perl 5 parser that you intend list context for the assignment even though you assign only one element of a list. This is subtle, but now that you know about it, the difference of amount context between these two statements should be obvious:
Evaluating a function or expression--except for assignment--in list context can produce confusion. Lists propagate list context to the expressions they contain. Both of these calls to find_chores()
occur in list context:
The latter example often surprises novice programmers, as initializing a hash (hashes) with a list of values imposes list context on find_chores
. Use the scalar
operator to impose scalar context:
Why does context matter? A context-aware function can examine its calling context and decide how much work it must do. In void context, find_chores()
may legitimately do nothing. In scalar context, it can find only the most important task. In list context, it must sort and return the entire list.
Perl's other context--value context--governs how Perl interprets a piece of data. You've probably already noticed that Perl's flexible about figuring out if you have a number or a string and converting between the two as you want them. In exchange for not having to declare (or at least track) explicitly what type of data a variable contains or a function produces, Perl's type contexts provide hints that tell the compiler how to treat data.
Perl will coerce values to specific proper types (coercion), depending on the operators you use. For example, the eq
operator tests that strings contain the same information as strings:
You may have had a baffling experience where you know that the strings are different, but they still compare the same:
The eq
operator treats its operands as strings by enforcing string context on them. The ==
operator imposes numeric context. In numeric context, both strings evaluate to 0
(numeric_coercion). Be sure to use the proper operator for the type of context you want.
Boolean context occurs when you use a value in a conditional statement. In the previous examples, if
evaluated the results of the eq
and ==
operators in boolean context.
In rare circumstances, you may need to force an explicit context where no appropriately typed operator exists. To force a numeric context, add zero to a variable. To force a string context, concatenate a variable with the empty string. To force a boolean context, double the negation operator:
Type contexts are easier to identify than amount contexts. Once you know which operators provide which contexts (operator_types), you'll rarely make mistakes.
Hey! The above document had some coding errors, which are explained below:
- Around line 3:
-
A non-empty Z<>
- Around line 7:
-
Deleting unknown formatting code N<>
Deleting unknown formatting code N<>
- Around line 34:
-
A non-empty Z<>
- Around line 152:
-
A non-empty Z<>