Lesson 8: Accessing elements of a hash


The beauty of hashes is that they enable us to retrieve specific information (value) for a given key. This is similar to a dictionary in that we can look up a 'word' to find the 'definition'. We do not have to go through all the other words to find the correct word. It is direct access.

1
2
3
4
5
# Example Hash:
my %favs = (    "band" => "Led Zeppelin",
                "book" => "Jitterbug Perfume",
                "language" => "Perl",
           );
key value
band Led Zeppelin
book Jitterbug Perfume
language Perl
  • To access only one element of the hash you are accessing a single scalar.
  • The $ and not the % will be used.
1
2
3
my $value = $favs{book};
print $value , "\n";
print "My favorite band is $favs{band}\n";

Output:

%% ./pieces_of_the_hash.pl
Jitterbug Perfume
My favorite band is Led Zeppelin
  • Notice the curly brackets {}.
  • {} indicate that we are accessing a piece of a hash.
  • The key in the {} will evaluate to one exact value.
  • %favs{band} is incorrect
  • $favs[band] is incorrect
  • %favs[band] is incorrect

Exercises

  1. Write a script in which you create a hash with 3 key/value pairs.
  2. print each value using a print statement with each key.
  3. assign two values to two new scalars.
  4. Add a print statement in which you print a sentence that uses the scalar variables

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *