Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I got this example from the Data::Compare module. It works really great except that I would want it to ignore only the 2nd element in the hash key (FOO) which means I would want the module to still compare the first element of hash key (FOO). Is there a way to do this?

The reason why I like Data::Compare is that my data structure is more complex than this example which is why I am trying to stick with it.
#!/usr/bin/perl use strict; use Data::Compare; my $h1 = { 'FOO' => [ 'one', 'two' ] }; my $h2 = { 'FOO' => [ 'one', 'three' ] }; print 'structures of $h1 and $h2 are ', Compare($h1, $h2, { ignore_hash_keys => [qw(FOO)] }) ? '' : 'not ', "close enough to identical.\n";

Replies are listed 'Best First'.
Re: Compare Data
by Khen1950fx (Canon) on Aug 03, 2011 at 05:57 UTC
    Data::Compare is very good, but I used FreezeThaw with its cmpStrHard method---it takes two distinct entities and compares them as a group. The way that I did it, I could slice, dice and ignore only the 2nd element, but that works out to be an exercise in futility. FreezeThaw will report that the groups are different in spite of ignoring that 2nd element. Here's what I tried:
    #!/usr/bin/perl use strict; use warnings; use FreezeThaw qw(cmpStrHard); my %a; my %b; %a = %b = ( 'this' => 'FOO', more => [ 'one', 'two' ], 'that' => 'FOO', more => [ 'one', 'three' ] ); $a{MORE} = \%b; $b{MORE} = \%a; printf "a and b contain %s hashes\n", cmpStrHard( \%a, \%b ) == 0 ? "the same" : "different";
Re: Compare Data
by JavaFan (Canon) on Aug 02, 2011 at 21:08 UTC
    According to the manual page, you cannot.
Re: Compare Data
by thewebsi (Scribe) on Aug 03, 2011 at 04:53 UTC

    Data::Compare doesn't seem to offer anything natively.

    However, you can get the result you want using:

    $h2->{FOO}->[1] = $h1->{FOO}->[1];

    before comparing.

    Of course, this modifies $h2. If you need to preserve $h2, then an option is:

    my $save = $h2->{FOO}->[1]; $h2->{FOO}->[1] = $h1->{FOO}->[1]; ... compare ... $h2->{FOO}->[1] = $save;

    However, if the number of exceptions is large, this may not be ideal. If you are not worried about efficiency, then you can make a copy of $h2 (using Data::Dumper::Deepcopy() perhaps), modify it as needed, and compare the result with $h1. As you mentioned that the real structure is complex, this may be too great a hit on performance / memory.