A simple hash is close to an array. Their initializations even look similar. Array first:
@last_name = ( "Ward", "Cleaver", "Fred", "Flintstone", "Archie", "Bunker" );
Now we will present the same information with a hash (aka associative array):
%last_name = ( "Ward", "Cleaver", "Fred", "Flintstone", "Archie", "Bunker" );
Although they have the same name, the array @last_name and the hash %last_name completely independent.
With an array, if we want to know the name of Archie, we need to perform a linear search:
my $lname; for (my $i = 0; $i < @last_name; $i += 2) { $lname = $last_name[$i+1] if $last_name[$i] eq "Archie"; } print "Archie $lname\n";
With a hash, it is much more direct syntactically:
print "Archie $last_name{Archie}\n";
Suppose we want to present information with only a slightly richer structure:
- Cleaver (last name)
- Ward (name)
- June (spouse's name)
- gravel
- Bunker
Before the links appeared, flat key hashes were the best we could do, but the links allow
my %personal_info = ( "Cleaver", { "FIRST", "Ward", "SPOUSE", "June", }, "Flintstone", { "FIRST", "Fred", "SPOUSE", "Wilma", }, "Bunker", { "FIRST", "Archie", "SPOUSE", "Edith", }, );
Internally, the keys and values โโof %personal_info are all scalars, but values โโare a special kind of scalar links: hash links created using {} . Links allow us to model "multidimensional" hashes. For example, we can get to Wilma through
$personal_info{Flintstone}->{SPOUSE}
Note that Perl allows us to omit the arrows between the indices, so the above is equivalent
$personal_info{Flintstone}{SPOUSE}
This is a lot of typing if you want to know more about Fred, so you can get the link as a kind of cursor:
$fred = $personal_info{Flintstone}; print "Fred wife is $fred->{SPOUSE}\n";
Because the $fred in the snippet above is hashref, an arrow is needed. If you leave this, but with smart inclusion use strict to help you catch such errors, the compiler will complain:
Global symbol "%fred" requires explicit package name at ...
Perl references are similar to pointers to C and C ++, but they can never be null. Pointers to C and C ++ require dereferencing, as well as references to Perl.
The parameters of the C and C ++ functions have pass-by-value semantics: they are just copies, so modifications do not return to the caller. If you want to see the changes, you need to pass a pointer. You can get this effect with links to Perl:
sub add_barney { my($personal_info) = @_; $personal_info->{Rubble} = { FIRST => "Barney", SPOUSE => "Betty", }; } add_barney \%personal_info;
Without a backslash, add_barney would get a copy that was thrown as soon as sub returned.
Also note the use of the bold point ( => ) above. It automatically prints the line to the left and makes hash initialization less syntactically noisy.