Pages

Basic stuff on arrays

Perl array is not so low level as its C counterpart, it would make more sense to compare it with C++ std::vector, but it is not defined in a library, instead it is a part of the language itself.

We see at once if a perl variable is an array or a scalar, since the name of an array starts with an at sign (@), while we know that a perl scalar variable name is introduced by a dollar sign ($).

We can initialize a string array a notation that remembers the C one, but it uses round brackets to delimit the elements:
my @names = ("Tim", "Bill", "Jim");
Or we can use a more perl-ish one, that gets rid of quotations and commas:
my @names = qw(Tim Bill Jim);
The result is the same: we have defined an array containing three strings.

When we want to print an array, we usually print it using the interpolated notation:
print "@names\n";
Because the interpolation in case of arrays means inserting a blank between each element - making the result readable.

One may wonder what means assigning an array to a scalar variable:
my $len = @names;
As the chosen variable names should suggest, an array variable in a scalar context is actually evaluated to the length of the array itself. So this perl instruction:
print "$len: @names\n";
should result in an output like this:
3: Tim Bill Jim
We didn't actually need an explicit scalar variable to achieve that result, we could just tell to perl to use the array as a scalar, using the "scalar" operator:
print scalar @names, ": @names\n";

Chapter 3 of Beginning Perl by Simon Cozens is about arrays and associative arrays (hashes).

No comments:

Post a Comment