Perl: Hash Table

By Xah Lee. Date: . Last updated: .

A hash table is a unordered collection of key and value pairs.

Create a Hash Table

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);  # load the Dumper function for printing array/hash

$Data::Dumper::Indent = 0;  # make it print in compact style

# hash table
%hh = ('john'=>3, 'mary'=> 4, 'joe'=> 5, 'vicky'=>7);

print Dumper \%hh;   # {'joe' => 5,'john' => 3,'vicky' => 7,'mary' => 4}

Variable of hash datatype must begin with % in their name.

If you are going to get values of a hash, you use $ in front of the hash variable. For example, $hash{'name'}.

The Dumper function's argument needs to be a “reference” to the hash. So, you can use it like this: Dumper(\%hash) or Dumper([%hash]). (parenthesis is usually optional)

Add/Modify a Entry

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4 );

$hh{'c'} = 5;

print Dumper \%hh;
# $VAR1 = {'c' => 5,'a' => 3,'b' => 4};

Delete a Entry

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# delete a entry
delete $hh{'b'};

print Dumper \%hh; # {'c' => 5,'a' => 3};

Check If Key Exist

# -*- coding: utf-8 -*-
# perl

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# check if a key exists
print exists $hh{'b'};  # 1
print exists $hh{'d'};  # (doesn't print anything)

Get Key's Value

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);

%hh = ('john' =>3, 'mary' => 4, 'joe' => 5);

# get value of a key
print $hh{'mary'};  # 4

Get All Keys

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# get all keys
print Dumper [keys %hh];  # ['c','a','b']

Get All Values

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# get all values
print Dumper [values %hh];  # [5,3,4]

Perl

Detail

String

Boolean

Conditional

Data Structure

Loop, Iteration

Function

Text Processing

Advanced

misc