Some expressions don't have a scalar-context value at all. For
example, what should sort return
in a scalar context? You wouldn't need to sort a list to count
its elements, so until someone implements something else, sort in a scalar context always returns
undef.
Another example is reverse. In a
list context, it gives a reversed list. In a scalar context, it
returns a reversed string (or reversing the result of concatenating
all the strings of a list, if given one):
@backwards = reverse qw/ yabba dabba doo /;
# gives doo, dabba, yabba
$backwards = reverse qw/ yabba dabba doo /;
# gives oodabbadabbay
At first, it's not always obvious whether an expression is
being used in a scalar or a list context. But, trust us, it will get to be second nature for you
eventually.
Here are some common contexts to start you off:
$fred = something; # scalar context
@pebbles = something; # list context
($wilma, $betty) = something; # list context
($dino) = something; # still list context!
Don't be fooled by the one-element list; that last one is a
list context, not a scalar one. If you're assigning to a list
(no matter the number of elements), it's a list context. If
you're assigning to an array, it's a list context.
Here are some other expressions we've seen, and the contexts
they provide. First, some that provide scalar context to something:
$fred = something;
$fred[3] = something;
123 + something
something + 654
if (something) { ... }
while (something) { ... }
$fred[something] = something;
And here are some that provide a list context:
@fred = something;
($fred, $barney) = something;
($fred) = something;
push @fred, something;
foreach $fred (something) { ... }
sort something
reverse something
print something