Lesson 9: Reassigning elements of a hash


Almost everytime you use a hash you will want to change the values of keys and add new key value pairs.

Code:

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/reassign only one element of the hash you are reassigning a single scalar variable.
  • The $ and not the % will be used.

Code continued:

1
2
3
4
5
6
7
## remember to add "use Data::Dumper;"
print Dumper \%favs;
 
$favs{book} = "Midnight in the garden of good and evil";
 
print "We just changed my favorite book\n";
print Dumper \%favs;

Add new key/value pairs at any time

Code continued:

1
2
3
4
$favs{movie} = "Natural Born Killers";
 
print "We just added my favorite movie\n";
print Dumper \%favs;

Output:

%% ./pieces_of_the_hash.pl
$VAR1 = {
          'language' => 'Perl',
          'band' => 'Led Zeppelin',
          'book' => 'Jitterbug Perfume'
        };
We just changed my favorite book
$VAR1 = {
          'language' => 'Perl',
          'band' => 'Led Zeppelin',
          'book' => 'Midnight in the garden of good and evil'
        };
We just added my favorite movie
$VAR1 = {
          'movie' => 'Natural Born Killers',
          'language' => 'Perl',
          'band' => 'Led Zeppelin',
          'book' => 'Midnight in the garden of good and evil'
        };

Exercises

  1. Write a script in which you create an hash with 3 key/value pairs and view your hash.
  2. Reassign 2 keys to contain new values and view the hash again.
  3. Add 2 new key/value pairs and view the hash again.

Print Friendly

Leave a Reply

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