Lesson 7: Hash Assignment


Remember, hashes are just like arrays with scalars as keys instead of numbers as indices.

key value
apple a
bee b
candy c
1
2
3
4
5
6
7
8
9
10
11
12
13
# hash_assignment.pl
 
# hash of strings
# assign values to a hash in a similar fashion to array
# the list is now a series of keys followed by it's value
my %first_hash = ("apple","a","bee","b","candy","c");
 
# a more intuitive way to assign key/value pairs to a hash
# the '=>' is a substitution for the ','
%first_hash = (  "apple" => "a",
                 "bee"   => "b",
                 "candy" => "c",
              );
  • In an array you can only have 1 of each index. You can only have one 5th element.
  • In a hash you also can only have 1 of each index or key. You can only have one bee-th element.

Visualizing the hash

  • We are going to use a module to help us see the structure of our hash.
  • use Data::Dumper;
  • we will use the method Dumper in our print statements
  • later, we will review other ways to print the contents of hashes
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
 
my %first_hash = (  "apple" => "a",
                 "bee"   => "b",
                 "candy" => "c",
              );
 
print Dumper \%first_hash;
# notice the '\'
# this is necessary for the Dumper method

Output:

%% ./hash_assignment.pl
$VAR1 = {
          'candy' => 'c',
          'apple' => 'a',
          'bee' => 'b'
        }

Exercises

  1. Create a script that contains a hash.
  2. View your hash with the module Data::Dumper

Print Friendly

Leave a Reply

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