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, 'jane' => 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
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable