Is there a reason you are using hashes and not arrays? I ask because your keys are only numbers, and nearly sequential numbers at that - this would seem to be the classic example of when to use arrays.

But, assuming you want to do this with hashes, you would first iterate over a sorted key list (see the FAQ How do I sort a hash (optionally by value instead of key)?) and then iterate over that list and output your desired result (How do I process an entire hash?). Something like:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash1 = ("1", "20", "2", "20", "4", "19", "5", "20", "6", "18"); my %hash2 = ("1", "19", "2", "20", "4", "16", "5", "19", "6", "20"); my %differences; for my $key ( sort {$a <=> $b} keys %hash1) { $differences{$key} = $hash1{$key} - $hash2{$key}; print "$key ($hash1{$key} - $hash2{$key}) = $differences{$key}\n"; } print "\n", Dumper \%differences; __END__ 1 (20 - 19) = 1 2 (20 - 20) = 0 4 (19 - 16) = 3 5 (20 - 19) = 1 6 (18 - 20) = -2 $VAR1 = { '6' => -2, '4' => 3, '1' => 1, '2' => 0, '5' => 1 };

and using arrays instead:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array1 = (undef,20,20,19,20,undef,18); my @array2 = (undef,19,20,16,19,undef,20); my @differences; for my $i (0 .. $#array1) { next unless defined $array1[$i]; $differences[$i] = $array1[$i] - $array2[$i]; print "$i ($array1[$i] - $array2[$i]) = $differences[$i]\n"; } print "\n", Dumper \@differences; __END__ 1 (20 - 19) = 1 2 (20 - 20) = 0 4 (19 - 16) = 3 5 (20 - 19) = 1 6 (18 - 20) = -2 $VAR1 = [ undef, 1, 0, 3, 1, undef, -2 ];

Update: Added storage of differences


In reply to Re: How best to compare hash values? by kennethk
in thread How best to compare hash values? by jimbass

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.