On Sat, 17 Mar 2012 08:17:56 -0500
Chris Stinemetz <chrisstinem...@gmail.com> wrote:

> Hello list,
> 
> I have two hashes that I would like to compare the values where the
> keys are the same. If there are any discrepancies I would like to
> print them. I have been struggling in find a solution. Below is what I
> have thus far:
> 
> #!/usr/bin/perl
> use warnings;
> use strict;
> use Data::Dumper;
> 
> my $firstFile = "out.txt";
> my $secFile = "outADD.txt";
> my $deltaFile = "datalinkDeltas.txt";
> 
> open my $firstFH,'<',$firstFile or die "ERROR opening $firstFile: $!";
> open my $secFH,'<',$secFile or die "ERROR opening $secFile: $!";
> open my $deltaFH,'>',$deltaFile or die "ERROR opening $deltaFile: $!";
> 
> my %firstFile;
> my %secondFile;
> 
> while (my $line = <$firstFH>) {
>       my ($k,$v) = split(/\s/,$line);
>       $firstFile{$k} = $v;
> }
> 
> while (my $line = <$secFH>) {
>       my ($k,$v) = split(/\s/,$line);
>       $secondFile{$k} = $v;
> }
> print Dumper (\%firstFile,\%secondFile);
> 

You can create this hash:

my %total_keys = (%firstFile, %secondFile);

Which will contain all keys.

And then do something like (untested):

foreach my $key (keys(%total_keys))
{
        if (exists($firstFile{$key})
        && !exists($secondFile{$key}))
        {
                print "Key '$key' is only in the first file.";
        }
        elsif (exists($secondFile{$key})
        && !exists($firstFile{$key}))
        {
                print "Key '$key' is only in the second file.";
        }
        elsif ($firstFile{$key} ne $secondFile{$key})
        {
                print "The values of '$key' in each hash differ.";
        }
}

Hope it helps. There are some modules on CPAN for deep-comparison of data
structures too.

Regards,

        Shlomi Fish
-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Chuck Norris/etc. Facts - http://www.shlomifish.org/humour/bits/facts/

COBOL is the old Java.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to