Hashes

Hashes are cool. Formally called “Associative Arrays” and referred to as a map (C++) or dictionary (Python), it is a lookup of a given key (numeric, string, or anything) to a value (or a reference to a more complex data structure).

my %hash = qw( red ff0000 green 00ff00 blue 0000ff );
my %hash = (red=>'ff0000', green=>'00ff00', blue=>'0000ff');
 
##### Using a Hash #####
print $hash{red};
$hash{white} = 'ffffff';
delete $hash{white};
@colors = keys %hash
@rrggbb = values %hash;
$hash_size = scalar keys %hash;
@vals = @hash{keys %hash};
print @hash{qw(key1 key2)};
 
##### Iteration and Loops #####
while (my ($k,$v) = each(%hash)) { print "$k=$v\n"; }
# Note that you should go through every element to reset 
# the "each", otherwise next time the loop will start where
# it previously ended. If you may break (last) from the loop, use
# the next form instead.
 
foreach my $k (sort keys %hash) { print "$k=$hash{$k}\n"; }
 
###### True or False? #####
 
if (%hash) ... # valued and has elements
if (exists $hash{white}) ... # Key exists in hash

References? Even cooler!

my $hash = \qw( red ff0000 green 00ff00 blue 0000ff );
my $hash = {red=>'ff0000', green=>'00ff00', blue=>'0000ff'};
 
##### Using a Hash #####
print $hash->{red};
$hash->{white} = 'ffffff';
delete $hash->{white};
@colors = keys %$hash
@rrggbb = values %{$hash};
$hash_size = scalar keys %$hash;
# $hash->{keys %hash}; # Invalid!
 
##### Iteration and Loops #####
while (my ($k,$v) = each(%$hash)) { print "$k=$v\n"; }
# See "each" note in previous section
 
foreach my $k (sort keys %$hash) { print "$k=$hash->{$k}\n"; }
 
###### True or False? #####
 
if (%$hash) ... # valued and has elements
if (exists $hash->{white}) ... # Key exists in hash
 
programming/perl/hashes.txt · Last modified: 2005/07/18 17:09 by allen