← Back to Perl Course | Chapter 2: Variables | Lesson 6 of 7

Context

The same expression can give a list or a single value depending on where you use it.

In this page:

  1. Context

Context

Perl has scalar context and list context, and many operations behave differently in each. An array in scalar context returns its number of elements, while in list context it returns all of them. You can force scalar context with scalar(), and assigning to a list in parentheses gives list context.

Note: my ($first) = @array takes the first element, but my $count = @array takes the count.

Example: Context

perl
use strict;
use warnings;

my @colors = qw(red green blue);

my $count = @colors;
my ($first) = @colors;
my $last_index = $#colors;
print "count=$count first=$first last_index=$last_index\n";
print "Colors: " . @colors . "\n";
print "Colors: @colors\n";
print "scalar reverse: ", scalar reverse("abc", "def"), "\n";
print "list reverse: ", join(",", reverse("abc", "def")), "\n";
my $matches = () = "banana" =~ /a/g;
print "number of a's: $matches\n";

# Output:
# count=3 first=red last_index=2
# Colors: 3
# Colors: red green blue
# scalar reverse: fedcba
# list reverse: def,abc
# number of a's: 3
Common Mistakes
  1. Writing my ($x) = @a and expecting the array length
  2. Printing an array in scalar context when you need its elements
  3. Not realizing reverse behaves differently in scalar context
Chapter Summary
  • Scalar context wants one value
  • List context wants many values
  • An array in scalar context is its length
  • Parentheses on the left side give list assignment
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.