Context
The same expression can give a list or a single value depending on where you use it.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing my ($x) = @a and expecting the array length
- Printing an array in scalar context when you need its elements
- 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: