< Perl Tutorial

Perl hashes

← Previous Next →


Perl Hashes

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, we will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets. In a hash the data is totally unsorted and has no intrinsic order. In fact, it's more like directory enquiries than a phone book in that we can easily find out what
the number is if we have the name. Someone else keeps the order for us, and we needn't ask what the first entry is. 
An example of a hash variable is as follows:

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);

print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

The above code gives the following output:

$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40

Hash Creation

Hashes can be created in one of the following two ways:

  1. First is by using an ordinary list of pairs.
    The following code demonstrates this method:
    %where=(
    "Gary" , "Dallas",
    "Lucy" , "Exeter",
    "Ian" , "Reading",
    "Samantha" , "Oregon"
    );

     

  2. If we want to make the relationship a little clearer, as well as highlighting the fact that we're dealing with a hash, we can use the => operator. Essentially, it's a comma, but whatever appears on the left hand side of it is treated as a double-quoted string.
    Following example demonstrates this method:
    %where=(
    Gary => "Dallas",
    Lucy => "Exeter",
    Ian => "Reading",
    Samantha => "Oregon"
    );

Accessing Hash Elements

When accessing individual elements from a hash, we must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. 
Following code shows how to access hash elements:

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";

The above code produces the following output:

45
30
40

Adding and Removing Hash elements

Adding a new key/value pair can be done by using simple assignment operator. But to remove an element from the hash we need to use delete function,
Following example demonstrates addition and deletion of hash elements:

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:  is $size\n";

# adding an element to the hash;
$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size:  is $size\n";

# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size:  is $size\n";

The above code produces the following output:

1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3
← Previous Next →