
Taking references to arrays or hashes is one way to build nested or multidimensional structures — but it isn’t necessary to actually use a reference to a named array or hash, Perl has anonymous arrays and hashes as well. To get one of these you use the anonymous array or hash composers — which are just the familiar [] for arrays and {} for hashes:
my $aref = [42, 37, 11];
my $href = {name => 'andrew', beer => 'dark ale'};
print "$aref->[1] $href->{name}\n"; #prints: 37 andrew
In these instances, the [] and {} simply create the structure in memory (either an array or a hash respectively) and return a reference to it — there is no array or hash variable. This makes specifying a nested structure rather easier. Recall last week’s simple example:
my @beer = ('dark-ale', 'pale-ale', 'stout');
my %hash = ( name => 'andrew', beer => \@beer);
print "$hash{name}'s favorite beer is $hash{beer}[0]\n";
print "$hash{name} will accept: @{$hash{beer}}\n";
This can now be done more directly (without the @beer array) as:
my %hash = ( name => 'andrew',
beer => ['dark-ale', 'pale-ale', 'stout'],
);
print "$hash{name}'s favorite beer is $hash{beer}[0]\n";
print "$hash{name} will accept: @{$hash{beer}}\n";
You do not have to specify the list explicitly within the [] or {} composers — any expression that returns a list may be used as well. This means we can easily read in a csv file and turn it into a table (a two dimensional array):
#!/usr/bin/perl -w
use strict;
my @data_table;
while(<DATA>){
chomp;
push @data_table, [split /:/];
}
# print out all rows:
foreach my $row (@data_table) {
print "@$row\n";
}
# print out second column of second row:
print "$data_table[1][1]\n";
__DATA__
one:two:three
four:five:six
seven:eight:nine
That sums up the brief tutorial on using references. For further information please see the following docs:
perldoc perlreftut
perldoc perlref
perldoc perllol
perldoc perldsc
I would also like to point out that version 5.6.1 is now available in the usual locations — this is a maintenance release in the stable track and fixes several bugs present in the 5.6.0 version.
I appreciate your suggestions for topics and tips — keep them coming. Next week we will look at speeding up certain kinds of functions by caching return values and look at the Memoize module.