Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Finding Common or Different Keys in Two Hashes

Problem

You need to find keys in one hash that are present in another hash or keys in one hash that are not present in another.

Solution

Use keys to loop through the keys of one hash, checking whether each key is also in the other hash.

Find common keys

my @common = ();
foreach (keys %hash1) {
	push(@common, $_) if exists $hash2{$_};
}
# @common now contains common keys

Find keys from one hash that aren’t in both

my @this_not_that = ();
foreach (keys %hash1) {
	push(@this_not_that, $_) unless exists $hash2{$_};
}

Discussion

Because we’re finding common or different keys of the hashes, we can apply our earlier array recipes for finding common or different elements to arrays of the hashes’ keys. For an explanation, see Section 4.8.

This code uses the difference technique to find non-citrus foods:

# %food_color per the introduction

# %citrus_color is a hash mapping citrus food name to its color.
%citrus_color = ( Lemon  => "yellow",
                  Orange => "orange",
                  Lime   => "green" );

# build up a list of non-citrus foods
@non_citrus = ();

foreach (keys %food_color) {
    push (@non_citrus, $_) unless exists $citrus_color{$_};
}

See Also

The “Variables” section of Chapter 2 of Programming Perl; the each function in perlfunc(1) and in Chapter 3 of Programming Perl

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata