DavidSzczesniak
1/3/2018 - 10:59 AM

Scalar and List Context

The context refers to how you use an expression.

# Basic example:
42 + something # That something must be a scalar
sort something # That something must be a list

# The same sequence of characters in both scalar and list context:
@people = qw( fred barney betty);
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # scalar context: 42 + 3(values inside @people) gives 45

# Context with ordinary assignment:
@list = @people; # a list of three people; list context
$n = @people; # the number 3; scalar context
\!h # Note: scalar context doesn't always just give the number of elements that would have been returned in list context

# Extra examples

# Scalar context:
$fred = something;
$fred[3] = something;
123 + something; 
something + 654;
if (something) {...}
while (something) {...}
$fred[something] = something;

# List context:
@fred =  something;
($fred, $barney) = something;
($fred) = something;
push @fred, something;
foreach $fred (something) {...}
sort something;
reverse something;
print something;