Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 43 ยท Scalars and Operators

Context: Scalar vs List

Understand Perl context: how the same expression returns different results in scalar and list context, wantarray, arrays as counts, and the common surprises.

Most programming languages ask what an expression is. Perl also asks where it is used. The same expression can produce a single value in one place and a whole list in another, and Perl decides based on the surrounding code. That surrounding situation is called context, and it is the idea that separates people who write Perl from people who guess at it.

You already use context without noticing. When you write my $count = @fruits; you get the number of elements, but with my ($first) = @fruits; you get the first element. The right-hand side is identical; only the left-hand side changed. This lesson gives you the rules, the handful of surprises you need to know, and wantarray, which lets your own subroutines react to context. We will use arrays here before the next chapter covers them in detail, so if a function looks unfamiliar, read Arrays alongside.

Perl is not installed on this site, so the Perl listings are read-only (their outputs come from real runs of Perl 5.42). The TryIt blocks use Python as a stand-in that models the rules.

Two contexts

Every operator and function in Perl is called in one of two contexts (plus a "void" case where the result is thrown away):

  • Scalar context: the code wants exactly one value, as in my $x = ... or $a + $b.
  • List context: the code wants zero or more values, as in my @x = ..., my ($a, $b) = ... or the arguments of print.

An expression is not "scalar" or "list" by itself. Its behavior changes with the context, and each operator documents what it does in each one.

Same code, two answers

Scalar context One value is wanted.
List context Any number of values.

The left-hand side picks the context.

1 / 2

Arrays in each context

The array is the classic example. In list context it gives you its elements. In scalar context it gives you its size.

PERL
use v5.36;

my @fruits = ("apple", "banana", "cherry");

my $count   = @fruits;      # scalar context: 3
my ($first) = @fruits;      # list context: "apple"
my @copy    = @fruits;      # list context: a copy of all elements

say $count, " ", $first;    # 3 apple

The parentheses around ($first) are what turn the assignment into a list assignment. Without them it is a scalar assignment and you get the count. This single pair of parentheses is a very common source of bugs, in both directions.

Often you need to force a context. The scalar function does that for scalars, and string concatenation with . already provides scalar context:

PERL
say "Count: " . @fruits;         # Count: 3
say "Count: ", scalar(@fruits);  # Count: 3
say "Items: @fruits";            # Items: apple banana cherry
if (@fruits > 2) { say "more than two" }

Inside double quotes, @fruits is interpolated as a list joined by spaces. @fruits > 2 compares numbers, so the array is in scalar context and means "the size". The index of the last element is $#fruits, which is 2 here.

A related trap is print, which takes a list:

PERL
my @a = (1, 2, 3);
print "Items: " . @a . "\n";   # Items: 3
print "Items: ", @a, "\n";     # Items: 123

The first line concatenates (scalar context, so the count). The second passes the elements to print one by one, which prints them with nothing between.

Python Array in scalar and list context (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same function, two meanings

Many built-in functions are context-sensitive, and the result in scalar context is not always "the size". Each function defines its own scalar behavior. Reading its documentation for both contexts is a habit worth building.

reverse is a good example. In list context it reverses the order of a list. In scalar context it concatenates its arguments and reverses the characters:

PERL
my $str = reverse "abc";          # scalar context: "cba"
my ($rs) = reverse "abc";         # list context: "abc" (one-element list)
say $str, " ", $rs;               # cba abc
say scalar reverse("abc", "def"); # fedcba
print "list: ", reverse("abc", "def"), "\n";   # list: defabc

That is why print reverse "hello" prints hello: print supplies list context, and reversing a list of one element changes nothing. Write print scalar reverse "hello" to reverse the text.

Other examples you will meet: localtime returns a 9-element list in list context and a readable date string such as Sat Nov 7 10:30:00 2026 in scalar context (see Dates and Times); a regex match with the /g flag returns all matches in list context but one match at a time in scalar context (see Captures and Modifiers); and sort has no defined behavior in scalar context, so do not rely on it.

Counting with the countof idiom

Sometimes you want to count how many items an expression produces, without keeping them. Assign to an empty list, then use that assignment in scalar context:

PERL
my $commas = () = "a,b,c,d" =~ /,/g;
say $commas;      # 3

A list assignment in scalar context returns the number of elements on the right-hand side, so () = ... throws the values away and my $commas = receives the count. It is often called the "countof" idiom, and you will see it in other people's code. The same rule explains this:

PERL
my $c = my ($p, $q) = (10, 20, 30);
say $c;           # 3  (three values on the right, even though two were stored)
Python Counting matches the countof way (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Subroutines that notice context

A subroutine can find out which context it was called in with wantarray. It returns a true value in list context, a false (but defined) value in scalar context, and undef in void context. Together with return, this lets you design functions that behave like the built-ins:

PERL
sub ctx {
    return wantarray ? "list" : defined(wantarray) ? "scalar" : "void";
}

my @l = ctx();   # list
my $s = ctx();   # scalar
ctx();           # void (the result is ignored)
say "$l[0] $s";  # list scalar

A realistic use is a function that returns details in list context and a summary in scalar context:

PERL
sub minmax {
    my @sorted = sort { $a <=> $b } @_;
    return wantarray ? ($sorted[0], $sorted[-1]) : "$sorted[0]-$sorted[-1]";
}

my ($lowest, $highest) = minmax(3, 9, 1);   # 1 and 9
my $range             = minmax(3, 9, 1);    # "1-9"

Use this sparingly. Callers must know the function behaves this way, and surprising context-dependent returns are a frequent cause of confusion. We will build on this in Subroutines.

Notice also that arguments to a function are in list context, so say "print: ", ctx(); calls ctx in list context and prints print: list. To force scalar context, wrap the call in scalar(...) or assign it to a scalar first.

Surprises and the golden rule

A few situations catch everybody once:

  • my $x = (7, 8, 9); is scalar context, so the comma operator evaluates each item and returns the last one. $x is 9, and Perl warns "Useless use of a constant (7) in void context". This is not the same as an array, which would return a count.
  • my ($first) = @list; and my $first = @list; look nearly identical and mean different things.
  • An empty array is false and a non-empty one is true in a condition, because the condition provides scalar context and the size is 0 or more. say "empty" unless @e; works for exactly this reason.
  • Interpolating a function call into a string needs @{[ ... ]}, which puts the call in list context. For scalar results, concatenate with . instead.

The golden rule that fixes nearly all of these:

Ask what the left-hand side or the surrounding operator wants, then check what the function returns in that context.

When you cannot tell, add parentheses or scalar to make your intent explicit, and use my ($x) = ... when you want the first value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given my @a = (5, 6, 7);, what do my $n = @a; and my ($n) = @a; store in $n?

    The scalar assignment gives the array scalar context, which is its size (3). The list assignment copies elements, so $n gets the first one (5).
  2. 2. What does wantarray return when a subroutine is called as my $x = f();?

    wantarray is true for list context, defined but false for scalar context, and undef for void context.
  3. 3. What is printed by print scalar reverse("abc", "def");?

    In scalar context reverse joins its arguments into "abcdef" and reverses the characters, giving "fedcba". The list version would print "defabc".
  4. 4. What does my $total = () = "a-b-c" =~ /-/g; store in $total?

    The match returns two dashes in list context, and a list assignment in scalar context returns the number of items on its right-hand side.

Summary

  • Context is the situation an expression is used in: scalar (one value) or list (any number).
  • An array gives its size in scalar context and its elements in list context; my ($x) = @a; takes the first element.
  • Each built-in defines its own scalar behavior, as reverse and localtime show.
  • () = ... in scalar context counts the results of an expression, and wantarray lets your own subs respond to context.
  • When in doubt, use scalar(...) or parentheses to state your intent.

Next: Arrays