in reply to How to compare two associative arrays efficiently

my %count; $count{$_}++ for keys(%a1), keys(%a2); my @not_common = grep { $count{$_} < 2 } keys %count;
We're building the house of the future together.

Replies are listed 'Best First'.
Re^2: How to compare two associative arrays efficiently
by viveks_19 (Initiate) on Oct 12, 2006 at 21:06 UTC
    thanks for your prompt reply,
    I was using the following code for comparision, I dont have any key or value pair and so that I compared all the entries (key and values). If they are not equal then I am pushing values from %pssn to an array. Please provide solution in this context.
    foreach $key(keys %pssn){ foreach $key1(keys %assn){ if ($key ne $key1){ push(@array,$key);} }} foreach $val(values %pssn){ foreach $val1(values%assn){ if ($ val ne $val1){ push(@array,$val);} }}

      Please use <c>...</c> around your code.

      Forget effeciency, your code doesn't even work. If both hashes are initialized to (a=>1, b=>2, c=>3), you end up with qw( b c a c a b 2 3 1 3 1 2 ) in @array instead of nothing.

      Update Ignore the remainder of this post based on new information provided in another post.

      The fix (assuming the values are strings) is below, although it's very weird that you want to merge the keys and the values.

      foreach my $key (keys %pssn) { if (not exists $assn{$key}) { push(@array, $key); } } foreach my $key (keys %assn) { if (not exists $pssn{$key}) { push(@array, $key); } } my %assn_vals = map { $_ => 1 } values %assn; my %pssn_vals = map { $_ => 1 } values %pssn; foreach my $val (keys %assn_vals) { if (not exists $pssn_vals{$val}) { push(@array, $val); } } foreach my $val (keys %pssn_vals) { if (not exists $assn_vals{$val}) { push(@array, $val); } }