Scalar and List Context
Context is the idea that makes Perl feel like a natural language. Every expression is evaluated either in list context (Perl wants a list of values) or scalar context (Perl wants exactly one value), and many operations return different things depending on which.
The same array, two answers
use strict;
use warnings;
my @guests = qw(ana ben cleo);
my @copy = @guests; # list context: all the elements
my $count = @guests; # scalar context: the number of elements
my ($first) = @guests; # list context (parentheses!): the first element
print "Copy: @copy\n";
print "Count: $count\n";
print "First: $first\n";Copy: ana ben cleo
Count: 3
First: ana
The left side of an assignment decides the context:
| Assignment | Context | Result for @guests |
|---|---|---|
my @x = @guests; |
list | all elements |
my $x = @guests; |
scalar | the count, 3 |
my ($x) = @guests; |
list | the first element |
The parentheses in my ($first) make a big difference. This is one of the most common Perl mistakes, so look out for it.
What creates which context
| Scalar context | List context |
|---|---|
| assigning to a scalar | assigning to an array, hash or (...) |
numeric/string operators (+, ., ==) |
arguments to print, push, most functions |
if, while conditions |
foreach (...) |
scalar(EXPR) |
sort, map, grep lists |
use strict;
use warnings;
my @items = (5, 10, 15);
if (@items) { # scalar context: count, true if non-empty
print "We have items\n";
}
print "Count plus one: ", @items + 1, "\n"; # + forces scalar context
print "Count: ", scalar(@items), "\n"; # force it explicitly
print "Elements: ", @items, "\n"; # print gives list context
print "Interpolated: @items\n";We have items
Count plus one: 4
Count: 3
Elements: 51015
Interpolated: 5 10 15
Notice that print @items joins the elements with nothing in between, while interpolating "@items" puts spaces between them.
Functions that care about context
Several built-ins return different things in each context:
use strict;
use warnings;
my @letters = qw(c a b);
my @rev_list = reverse @letters; # list: reversed elements
my $rev_str = reverse "stressed"; # scalar: reversed string
print "@rev_list | $rev_str\n";
my $date_str = gmtime(0); # scalar: a readable date string
print "$date_str\n";
my @parts = gmtime(0); # list: (sec, min, hour, mday, mon, year, ...)
print "Year field: $parts[5] (that is ", $parts[5] + 1900, ")\n";
my %ages = (tom => 30, ann => 25);
my $n_keys = keys %ages;
print "Hash has $n_keys keys\n";b a c | desserts
Thu Jan 1 00:00:00 1970
Year field: 70 (that is 1970)
Hash has 2 keys
gmtime(0) describes the moment 0 of Unix time, 1 January 1970. In scalar context the same function returns a readable string instead.
A classic trap: reverse in print
print provides list context, so reverse reverses the list of its arguments, not the characters:
use strict;
use warnings;
my $word = "drawer";
print reverse($word), "\n"; # list of one item: unchanged
print scalar(reverse($word)), "\n"; # scalar context: reversed stringdrawer
reward
wantarray: writing context-aware subs
Your own subroutines can check their context with wantarray, which is true in list context and false in scalar context:
use strict;
use warnings;
sub top_scores {
my @sorted = sort { $b <=> $a } (88, 92, 75, 99);
return wantarray ? @sorted[0 .. 2] : $sorted[0];
}
my @top = top_scores();
my $best = top_scores();
print "Top three: @top\n";
print "Best: $best\n";Top three: 99 92 88
Best: 99
Use this sparingly: subs that behave differently in each context can be confusing. But understanding it explains how built-ins such as localtime and reverse work.
Test yourself
Given my @a = (4, 5, 6);, what is in $x after my $x = @a;?
- 4
- 6
- 3
4 5 6
And after my ($y) = @a;?
- 4
- 3
- 6
- undef
Why does print reverse("abc"); print abc?
reverseonly works on arraysprintgives list context, so reverse reverses a one-element list- Strings cannot be reversed
- It is a bug in Perl