What's a hash?
- Also called "associative arrays", but one syllable beats seven
- Made up of "values" indexed by "keys"
- Values can be any scalar
- Keys are strings, and case-sensitive
- Variables are prefixed with a percent sign
- Hashes are stored in arbitrary order
When to use a hash
- Quick lookups
print $books{
"1-56592-243-3" }; looks up an ISBN
- Storing info about an object. Hashes are an "of"
relationship.
$person{ "age" } =
31; can be read as "The age of the $person is 31."
- Checking for duplicates
Putting things in hashes
- Assigning a value to a hash element creates it:
my %stats;
$stats{ "name" } = "Andy Lester";
$stats{ "age" } = 31;
- You can create a hash by using a list of key-value pairs:
my %stats = ( "name", "Andy Lester", "age", 31 );
# Identical to example above
- Values are always scalars
my @friends = qw( Mike Laura Tweavis );
$stats{ "friends" } = @friends; # wrong!
# At this point, $stats{"friends"} is 3.
- You can store lists in a hash by making a reference to a list, but
that's a future topic.
Getting things out of hashes
- Refer to a hash key to get its element.
print "My name is ", $stats{ "name" },
" and I'm ", $stats{ "age" };
# prints "My name is Andy Lester and I'm 31"
- Referring to a non-existent element returns the special value undef . Printing undef gives a blank string, but
the use strict; pragma
will catch it.
print "My name is ", $stats{ "name" },
" and I live at ", $stats{ "address" };
# Prints "My name is Andy Lester and I live at"
- Check for existence of an element using the defined() function
if ( defined $stats{ "address" } ) {
print "My address is ", $stats{ "address" };
}
|
|
|