Perl Hashes
Hash Tables - Introduction
- Provide tables of (key, value) pairs
- Like an array, but you index values using keys rather than integers
- Keys are strings (but numbers can be converted to strings)
- Values can be anything
Creation, Access Elements, Existence, Adding Element
# Create a hash table of state capitals
%caps = (
va => 'richmond', # Keys are strings by default
nc => 'raleigh'
);
# Print an element
# Notice the $ and {}
print $caps{'va'}; # prints richmond
# Check if an element exists in the table
exists $caps{'va'}; # evaluates to 1 (ie true)
exists $caps{'VA'}; # evaluates to "" (ie false)
# Add an element to the table
$caps{'tn'} = 'nashville',
print $caps{'tn'}; # prints nashville
Removing an Entry
# Two ways to remove an entry:
$caps{'nc'} = undef;
delete $caps{'nc'};
Other Creation Methods
# Another way to create the table of capitals
%caps2 = ( 'va', 'richmond', 'nc', 'raleigh');
print $caps2{'va'}; # prints richmond
# Yet another way to create the table of capitals
# Remember qw is quoteword
%caps3 = qw( va richmond nc raleigh);
print $caps3{'va'}; # prints richmond
print join ", ", %caps; # va, richmond, nc, raleigh, tn, nashville
Accessing all Pairs: Function each
%caps = (
va => 'richmond', # Keys are strings by default
nc => 'raleigh',
tn => 'nashville'
);
# Prints values in sequence.
# function each returns each pair in table.
while ( ($state, $cap) = each %caps)
{
print "$state, $cap";
}
Accessing all Keys: Function keys
# Prints pairs in table, sorted by key (ie state)
# function keys returns a list of the table's keys
foreach $state (sort keys %caps)
{
print "$state, $caps{$state} ";
}
Accessing all Values: Function values
# Prints all values in table
foreach $aCap (sort values %caps)
{
print "$aCap ";
}
Lookup by Value: Must invert table
# First attempt at looking up the key for a given value
foreach $aCap (sort values %caps)
{
print "$aCap, $caps{$aCap} ";
}
# Whoops, tries to look up by capitals
# Prints 3 (caps, null string) pairs
# Need to invert caps table for this to work. Can invert using a
# reversed key value pair list to create a new list, something like
# The long way:
@caps = %caps ; # Flattened list of all key, value pairs
@revcaps = reverse @caps ;
%revcaps = @revcaps; # Create the new table
# The short way:
%revcaps = reverse %caps
while ( ($state, $cap) = each %revcaps)
{
print "$state, $cap; ";
}
What can go wrong?