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

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.

Next: Conditions and comparison

Article author: Arthur Isaev