Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise: Function to compare two hashes

Create a function that given two hashes, returns a report showing missing keys or keys with different values.

#!/usr/bin/env perl
use strict;
use warnings;

my %x = (
    foo    => 1,
    bar    => 2,
    baz    => 3,
    zoo    => 6,
    foobar => undef,
    moose  => undef,
);
my %y = (
    foo    => 1,
    bar    => 4,
    moo    => 5,
    zoo    => undef,
    foobar => 9,
    moose  => undef,
);

my @report = compare_hashes(\%x, \%y);
print join "\n", @report;
print "\n";
The value of 'bar' differs: '2' and '4'
The key 'baz' does not exist in second hash
The value of 'zoo' is '6' in the fist has and undef in the second hash
The value of 'foobar' is '9' in the second has and undef in the first hash
The key 'moo' does not exist in first hash