Context: Scalar vs List

Context is fundamental in Perl: the same expression returns different things depending on whether a single value (scalar context) or a list (list context) is expected.

Number of elements Key/value pairs Count of keys (5.26+; a fraction string in older Perls)

(sec, min, hour, mday, mon, year, wday, yday, isdst) "Fri Oct 24 10:30:00 2025" Reversed concatenated string All remaining lines m// (without /g) Next match (iterates) (1, 2, 3) literal Last element (comma operator)

Void context: the result is discarded. wantarray returns undef.

my @arr = (5, 6, 7);
my $count = @arr;            # 3 (scalar context)
my ($first) = @arr;          # 5 (list context)
my $str = "Items: " . @arr;  # "Items: 3" (concatenation imposes scalar context)
if (@arr) { ... }            # boolean context: true if non-empty
my $time = localtime;        # scalar: string
my @parts = localtime;       # list: components
say scalar(@arr);            # force scalar context
my $n = () = $text =~ /\w+/g;   # "countof" idiom: count matches

sub ctx { return wantarray ? 'list' : defined(wantarray) ? 'scalar' : 'void' }
my @l = ctx();  my $s = ctx();  ctx();