FreeKB - Getting Started with Hashes
Perl - Getting Started with Hashes

A hash, or more technically an associative array, is a collection of key:value pairs. For example, let's say you want to create the following key:value pairs.

name: John Doe
id: 123456
department: engineering

 

You can create an empty hash and then append key:value pairs to the hash. This is the common approach. Or you can create a hash that contains key:value pairs.

 


Here are different ways to create an empty hash named "hash".

my %hash;
my %hash = ();

 

key:value pairs can be appended to the hash, like this.

%hash = (
  name => "John Doe", 
  id => "123456", 
  department => "engineering"
);

 

Or, like this.

$hash{"name"}       = "John Doe";
$hash{"id"}         = "123456";
$hash{"department"} = "engineering";

 

An if statement can be used to confirm that the hash is not empty.

if (keys %hash) { 
  my $size = keys $hash;
  print "\%hash is not empty (contains $size keys)\n"; 
}

 


Dumper

Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper \%hash;

 

Which will display the data structure of the hash.

$VAR1 = {
           'name' => 'John Doe',
           'id' => '123456',
           'department' => 'engineering'
        };

 

Or, you can print the value of a key. For example, the following will print the value in the "name" key (Jeremy).

print $hash{"name"};

 


Loop through keys / values

You will usually want to loop through the hash.

 


Hash arrays

Each hash key will contain a single value. If you were to do this . . .

%hash = (
  name => "John Doe", 
  id => "123456", 
  department => "engineering"
);

%hash = (
  name => "Jane Doe", 
  id => "987654", 
  department => "sales"
);

 

Or this . . .

$hash{"name"} = "John Doe";
$hash{"name"} = "Jane Doe";

 

The hash would only contain the record for Jane Doe.

$VAR1 = {
           'name' => 'Jane Doe',
           'id' => '987654',
           'department' => 'sales'
        };

 

You can store the hash in an array. 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 919b1 in the box below so that we can be sure you are a human.




Comments