Context
Context is Perl's single most distinctive concept, and it has no real equivalent anywhere else on this site. Every expression in Perl is evaluated in either scalar context (one value is expected) or list context (a list of values is expected) — and many expressions, arrays chief among them, produce a completely different result depending on which context they're evaluated in.
use strict; use warnings; my @array = (1, 2, 3, 4, 5); my $count = @array; my ($first, $second) = @array; print "Count (scalar context): $count\n"; print "First two (list context): $first, $second\n";
Count (scalar context): 5 First two (list context): 1, 2
my $count = @array; assigns to a single scalar, so Perl evaluates @array in scalar context — and an array in scalar context yields its element count, 5. my ($first, $second) = @array; assigns to a list of scalars, so Perl evaluates @array in list context — and an array in list context yields its actual elements, taken in order. Same variable, same line structure, two entirely different results, purely because of what's on the left-hand side of the assignment.
Context shows up everywhere once you know to look for it: a boolean test (if (@array)) evaluates an array in boolean context, which is really scalar context underneath — an array with zero elements is false, any non-empty array is true, regardless of what the elements actually are. String concatenation with . also forces scalar context on its operands.
use strict; use warnings; my @empty = (); my @full = (1, 2, 3); print "empty is true\n" if @empty; print "full is true\n" if @full; print "Interpolated (list context): @full\n"; print "In scalar context: " . @full . "\n";
full is true Interpolated (list context): 1 2 3 In scalar context: 3
Interpolating @full inside a double-quoted string joins its elements with spaces (list context), while "..." . @full . "..." forces @full into scalar context first, giving its count (3), then concatenates that number into the string. Keeping half an eye on "is this scalar or list context?" is one of the biggest adjustments coming to Perl from any other language on this site. Next: subroutines.
Practice exercise
Given my @items = ("a", "b", "c", "d"), assign my $count = @items (scalar context) and print it, then print the full list joined by "-".