Context: Scalar vs. List
In Perl, code behaves differently depending on what is expected of it on the receiving end. This behavior is called Context. There are two primary contexts: Scalar Context and List Context.
"Perl evaluates expressions depending on whether a singular thing or multiple things are expected."
1. Scalar Context (Singular)
If you assign an expression to a singular scalar variable ($), the expression runs in a scalar context. When evaluated this way, arrays return their **length** (the count of elements):
use strict;
use warnings;
my @users = ("Alice", "Bob", "Charlie");
# Expected output is a singular scalar:
my $user_count = @users;
print "$user_count\n"; # Outputs: 3
2. List Context (Plural)
If you assign an expression to an array (@) or a parenthesized list of variables, the expression runs in a list context. Evaluated this way, arrays return their **actual elements**:
# Expected output is a list:
my @copy_of_users = @users;
# Assigning to individual variables:
my ($first, $second) = @users;
print "First user is $first\n"; # Outputs: First user is Alice
The `scalar` Built-in Function
If you are inside a list context but want to force Perl to interpret an expression as a singular value anyway, wrap it in the scalar helper function:
# Normally print expects a list, but we can force scalar evaluation:
print scalar @users; # Outputs: 3