PERL / CHAPTER 04
Context-sensitive interfaces
IntermediateReason about list, scalar, and void callers.
By the end of this chapter
- Trace context passed into a subroutine
- Interpret wantarray’s three outcomes
- Prefer explicit result shapes when ambiguity is costly
The idea
Perl evaluates expressions in a context supplied by their caller. List context requests a list, scalar context requests one scalar value, and void context ignores the result. A subroutine can inspect that context with wantarray, which is true for list context, false for scalar context, and undefined for void context. Context is a semantic input even though it is not written in the argument list.
Context-sensitive interfaces can be convenient, but they can also make a harmless-looking assignment change behavior. Document what each context means and avoid guessing that scalar context always selects the final item; the expression or subroutine defines its scalar behavior. Returning a reference gives callers one stable container when a result should preserve the same structure everywhere.
use strict; use warnings;
sub pair { return wantarray ? (2,5) : 7; }
my @items=pair();
my $total=pair();
print join(",",@items),"\n",$total,"\n";2,5 7
The array assignment requests list context, while the scalar assignment selects the explicitly defined scalar result.
Try it yourself
Design a result API returning one array reference regardless of caller context.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING