Maps in Perl

Our first program demonstrates how to work with maps in the target language, Perl. Here’s the full source code.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

# To create an empty hash, just use empty parentheses.
my %m = ();

# Set key/value pairs using typical hash syntax.
$m{"k1"} = 7;
$m{"k2"} = 13;

# Printing a hash with Dumper will show all of its key/value pairs.
print "map: ", Dumper(\%m);

# Get a value for a key with $hash{key} syntax.
my $v1 = $m{"k1"};
print "v1: $v1\n";

# If the key doesn’t exist, the default value returned is undef.
my $v3 = $m{"k3"};
print "v3: ", defined $v3 ? $v3 : "undef", "\n";

# The keys function returns the number of key/value pairs.
my $len = keys %m;
print "len: $len\n";

# The delete function removes key/value pairs from a hash.
delete $m{"k2"};
print "map: ", Dumper(\%m);

# To remove all key/value pairs from a hash, simply undefine it.
%m = (); 
print "map: ", Dumper(\%m);

# Checking if a key exists in the hash.
my $prs = exists $m{"k2"};
print "prs: ", $prs ? "true" : "false", "\n";

# Declare and initialize a new hash with this syntax.
my %n = (
    "foo" => 1,
    "bar" => 2,
);
print "map: ", Dumper(\%n);

# Compare two hashes using a custom function.
sub hashes_equal {
    my ($a, $b) = @_;
    return 0 unless keys %$a == keys %$b;
    foreach my $key (keys %$a) {
        return 0 unless exists $b->{$key} && $a->{$key} == $b->{$key};
    }
    return 1;
}

my %n2 = (
    "foo" => 1,
    "bar" => 2,
);

if (hashes_equal(\%n, \%n2)) {
    print "n == n2\n";
}

To run the program, save the code in a file with a .pl extension and execute it using the Perl interpreter.

$ perl maps.pl
map: $VAR1 = {
  'k1' => 7,
  'k2' => 13
};
v1: 7
v3: undef
len: 2
map: $VAR1 = {
  'k1' => 7
};
map: $VAR1 = {};
prs: false
map: $VAR1 = {
  'bar' => 2,
  'foo' => 1
};
n == n2

Note that maps (or hashes in Perl) appear in the form {k => v, k => v} when printed with Data::Dumper.

Now that we can run and build basic Perl scripts, let’s learn more about the language.