Scalar and list context
Two contexts
A Perl expression is always evaluated in a context, and the context is decided by what surrounds it. On the left of an equals sign a list expects many values; a scalar expects one.
This is not an optimization detail. It is the rule that explains why the same function returns a count in one line and a list in the next.
my @all = (1..5); # list context my $count = @all; # scalar context: 5 my $last = (1..5); # scalar context: the flip-flop, empty here print "$count\n"; # 5 print "no value\n" unless $last; # no value
perl demo.pl
5
no value
The last line trips up everyone once. Parentheses do not create a list; they only group. In scalar context the range operator stops being a range: .. turns into the flip-flop operator, which asks whether the current input line number $. lies between its two sides. This script reads no input, so $. is undef, the test is false, and $last stays empty - it is not 5.
The operator that returns its rightmost value is the comma, and it needs separate values, not a range:
my $third = (1, 2, 5); # comma operator: 5 print "$third\n"; # 5
perl demo.pl
5
Same function, two answers
Many built-ins read the context and answer accordingly. keys is the classic: a list of keys when you want them, a count when you do not.
my %h = (a => 1, b => 2); my @k = keys %h; # ("a", "b") in some order my $n = keys %h; # 2 my @tail = split /,/, "a,b,c"; # three fields
Reading files has the same shape: in list context a file read returns every remaining line, in scalar context only one. Long files make that difference expensive, which is why line-by-line loops are the default in lesson 6.1.
Forcing scalar context
When you need the scalar answer in a list position, say so with scalar. It is also the clearest way to document intent for the next reader.
my @words = qw(a b c); print scalar @words, " words\n"; # 3 words print "items: ", scalar( grep { $_ gt "a" } @words ), "\n";
perl demo.pl
3 words
items: 2
Do not add scalar to every function call. In an argument list it can change behavior, such as making reverse turn a string around instead of a list.
wantarray
Your own subroutines can ask the same question. The wantarray built-in returns true in list context, false in scalar context, and undef in void context, where the caller ignores the result.
sub stats { my @nums = @_; return wantarray ? @nums : scalar @nums; } my $n = stats(1, 2, 3); # 3 my @n = stats(1, 2, 3); # (1, 2, 3) print "$n\n"; print "@n\n";
perl demo.pl
3
1 2 3
Use this sparingly. A function that behaves differently depending on where it is called is convenient, and also the source of the strangest bugs in Perl code. Most subroutines should return one predictable thing.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What decides the context of a Perl expression?
Answer
What surrounds it: a list on the left of
=expects many values, a scalar expects oneContext is decided by the surrounding expression, which is why the same call answers differently in two lines.
-
Do parentheses around a range create a list?
Answer
No: parentheses group, and the context still decides how the inside is evaluated
Parentheses do not change context, so
my $x = (1..5)asks the range for a scalar and gets the flip-flop instead. -
What happens to the range operator in scalar context?
Answer
It becomes the flip-flop operator, which tests the input line number against its two sides
That is why
my $last = (1..5)is not 5; with no input the test is false and the value stays empty. -
How do you ask for the scalar answer of an array in a list position?
Answer
scalar @wordsscalarforces scalar context and documents the intent to the next reader. -
What does
wantarrayreturn in void context, where the caller ignores the result?Answer
undef
It is true in list context and false in scalar context; in void context the answer is undef, which is false but distinct.
-
Why is a line-by-line file loop the default rather than
my @lines = <$fh>?Answer
A file read in list context returns every remaining line, so a long file is read into memory at once
Context decides the cost: one line in scalar context, the whole rest of the file in list context.
-
What does this program print?
my @all = (1 .. 5); my $count = @all; print "$count\n";Answer
5
Assigning an array to a scalar asks for the element count, which is 5.
-
What does this program print?
my $third = (1, 2, 5); print "$third\n";Answer
5
The comma operator returns its rightmost value, so the parentheses hand 5 to the scalar.
-
What does this program print?
my %h = (a => 1, b => 2, c => 3); my $n = keys %h; print "$n\n";Answer
3
In scalar context
keysreturns the number of keys, not the first key. -
What does this program print?
my $last = (1 .. 5); print $last ? "value" : "empty", "\n";Answer
empty
The flip-flop returns an empty string here, which is false, so the ternary takes the second branch.
Article author: Arthur Isaev