There are many expressions that would typically be used to produce a list. If you use one in a scalar context, what do you get? See what the author of that operation says about it. Usually, that person is Larry, and usually the documentation gives the whole story. In fact, a big part of learning Perl is actually learning how Larry thinks. 1 Therefore, once you can think like Larry does, you know what Perl should do. But while you're learning, you'll probably need to look into the documentation.
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
Next: Using Scalar_Producing Expressions in List Context
[1]
This is only fair, since while writing Perl he tried to think like you do to predict
what you would want!
Return to the page from whence you came