Re: How to compare hashes to find matching keys with conflicting values.
Why don't you compare each key directly without transforming them to an
array?
if ($actual{host1} eq $register{host1}) {
do something;
}
else...
OR
foreach (keys %actual) {
if ($actual{$_} eq $register{$_}) {
do something;
}
}
Marcel
Angus wrote:
> Hello,
>
>
>
> I am trying to write a little script that will compare two hashes with the
> same keys but conflicting values. I have found some great examples of how
> to compare hashes and locate common keys or missing keys (in the cookbook).
> I have also found a great example of how to locate duplicate keys in two
> hashes (also in the cookbook) but nothing that helps with this question in
> particular. The following example is based on a pair of hashes using
> hostname and ip address information.
>
>
>
> #!/usr/bin/perl
>
> use strict;
>
> use warnings;
>
>
>
> # This hash represents the actual data, in other words what the machines
> have acquired for an ip address.
>
> my %actual = (
>
> "host1" => "192.168.119.175",
>
> "host2" => "192.168.123.43",
>
> "host3" => "192.168.45.98",
>
> "host4" => "192.168.98.89",
>
> "host5" => "192.168.67.123",
>
> );
>
>
>
> # This hash represents the preferred information, or what I would like to
> assign to my hosts.
>
> my %register = (
>
> "host1" => "192.168.119.179",
>
> "host2" => "192.168.21.43",
>
> "host3" => "192.168.45.98",
>
> "host4" => "192.168.8.89",
>
> "host5" => "192.168.67.123",
>
> );
>
>
>
> My @common = (); # it seems with this I at least have an array that now
> maintains a list of host names that definitely exist in both hashes
>
> Foreach my $host (keys %actual) {
>
> Push (@common, $host) if exists $register{$host);
>
> }
>
>
>
> # I also sort of wondered if I could use the values function to compare the
> hashes but this just resulted in an array with every element in it.
>
> My @not_common = ();
>
> Foreach my $host (values %actual) {
>
> Push(@not_common, $host) unless $register{$host} == $host; }
>
> Print "@not_common\n";
>
> # but as I am sure you can imagine this doesn't work so well..
>
>
>
> # at this point I think I should use references to insert the host name and
> compare the hosts but I am not sure how I would do this.
>
> # so what I thought might also work is simply comparing the two hashes like
> this
>
> My @match = ();
>
> If ($actual{$host1} == $register{$host1}) {
>
> Print "They match!\n";}
>
> Else {
>
> Print "no match. \n";}
>
>
>
> # The print statements are just tests, if it had worked I thought I could
> open a filehandle to a flat file and write out the match and conflicts.
>
>
>
> So, hopefully that is enough to explain what I am trying to do in spite of
> my feeble attempts to solve the question.
>
>
>
> Thanks in advance to anyone willing to point out the err my ways,
>
>
>
> -a
.