Hashes
- Arrays indexed on arbitrary string values, rather than on ordered integers
- aka associative arrays, maps
- Stored and accessed based on key - value pairs
- Hashes have no particular internal order
- Can't push or pop a hash
- Prefixed by
%to refer to the entire hash - Prefixed by
$to refer to an indexed element of the hash
%hash1 # the entire hash
$hash1{"str"} # the element at index {"str"}
exists $hash{$key} # Test if the hash key exists
scalar(keys(%hash1)) # number of keys
my %hash = (apple => 'red'); # Named hash (parentheses)
{apple => 'red'}; # Reference to an anonymous hash (curly braces)
{%hash}; # Reference to an anonymous copy of the hash (curly braces)
my %fruit_color = ("apple", "red", "banana", "yellow");
my %fruit_color = (
apple => "red",
banana => "yellow",
);
my $fruit_color_ref = { # Reference to an anonymous hash (using curly braces instead of parentheses)
apple => "red",
banana => "yellow",
};
$fruit_color{"apple"}; # Retrieve an existing value ("red").
$fruit_color{"apple"} = "green"; # Update an existing key-value pair.
$fruit_color{"cherry"} = "red"; # Insert a new key-value pair.
delete $fruit_color{"banana"}; # Delete an existing key-value pair.
undef %fruit_color; # Delete the entire hash.
my @fruits = keys %fruit_colors; # Array of keys
my @colors = values %fruit_colors; # Array of values
my %hash = (); # Empty hash
my $hash_ref = {}; # Reference to an anonymous empty hash (using curly braces instead of parentheses)
foreach my $key (keys %hash) { # Print a hash using foreach
print "$key = $hash{$key}\n";
}
while (($key, $value) = each %hash) { # Print a hash using while-each
print "$key = $value\n";
}
print map "$_ = $hash{$_}\n", keys %hash; # Print a hash using map
#Convert a hash reference into a formatted string: key1 => "one", ...
sub hash_to_string {
my $hash_ref = shift;
my $str = '';
foreach my $key (keys %$hash_ref) {
$str .= $key . " => " . $hash_ref->{$key} . "\n";
}
return $str;
}
# Sample use
my %hash = (
two => 'deux',
three => 'trois',
);
print hash_to_string(\%hash); # Pass a reference to the hash
print hash_to_string( {two => 'deux', three => 'trois'} ); # Pass a reference to an anonymous hash (curly braces)
print hash_to_string( {%hash} ); # Pass a reference to an anonymous copy of the hash
Resources URL:
notes/perl/resources
Sources URL:
notes/perl/sources