Perl Script : List literals

List literals
One way to assign a value to an array variable is to use a list literal. A list literalis an expression that yields a list value. Here is the standard list example.
my @list = (1, 2, 3);
print "@list\n";

Most of the time, you can pretend that lists and arrays are the same thing.
There are some differences, but for now the only one we are likely to run into is this: when you evaluate a list in a scalar context, you get the last element of the list. The following program prints 3.
my $scalar = (1, 2, 3);
print "$scalar\n";

But when you assign a list to an array variable, the result is an array value. Sothe following program prints the length of the list, which is 3.
my @list = (1, 2, 3);
my $scalar = @list;
print "$scalar\n";
The difference is subtle.

No comments:

Post a Comment