Perl: Hash Table

By Xah Lee. Date: . Last updated: .

In Perl, keyed-list is called hash table, or just hash. It is done like this:

Creating a hash table.

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

use Data::Dumper qw(Dumper); # load Data::Dumper, for printing array/hash
$Data::Dumper::Indent = 0;   # make it print in compact style

# create a hash table
%hh = ('a' =>3, 'b' => 4, 'c' => 5);
print Dumper \%hh;  # {'c' => 5,'a' => 3,'b' => 4};

Get value of a key:

# -*- 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

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};

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]

Check if a key exist:

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

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

%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)

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)

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email