
Lists and Arrays
Author: John M. Gabriele | back to index
---
It's easy to get confused by the terminology of lists and arrays. I learned the difference a while back from a post by Dominus on PerlMonks: http://www.perlmonks.org/?node_id=72263.
The executive summary is as follows.
Expressions vs. Values
Expressions are text you write in your source code. Values are what
perl makes of them after compiling and interpreting.
Compile-time vs. Run-time
An expression's context is determined only at compile-time.
Only values are in the interpreter's memory at run-time; context is irrelevant at run-time.
Some examples of expressions and their values
@aThis is an array expression. In list context, it evaluates to a list. In scalar context, you get the size of that list.
('a', 'b', 42)This is a comma expression, enclosed in parentheses. The parenthesis are for grouping (recall that the comma operator has very low precedence). In list context, this expression evaluates to a list. In scalar context, it evaluates to the last item on the right.
'a', 'b', 42This is also a comma expression, but since there's no parentheses, the low precedence of the comma operator usually breaks it up into pieces. For example, in
my $foo = 'a', 'b', 42;
$foogets the value 'a', thenperlevaluates the other two expressions and does nothing with them. Likewise, inmy @bar = 'a', 'b', 42;
it's the same thing as
my @bar = 'a'; # @bar gets the one-item list ('a'). 'b', 42; # Does nothing.@c[ ... ]This is an array slice expression. In list context, it evaluates to a list. In scalar context, you get the last item pulled out of
@c(just like a comma expression in parentheses).some_func()This is a function call expression. How it behaves in scalar and list contexts depends on the implementor. At compile-time,
perltells the function how it plans on calling it (that is, the context it's being called in), and figures out the appropriate compiled code for that function based on that context.