First, you have nested your loops so you are comparing each element of the first array against all of the elements of the second array. Unless all of your hashes are identical (rather than just each pair), most of them will be reported as "changed".

Second, = is an assignment operator. Perhaps that was just a typo and you meant == which does a numeric comparison. But you should really use eq which is much more general (compares strings).

Here is some code. I'm not sure I correctly deciphered what you want to do when you find a difference.

#!/usr/bin/perl -w use strict; use Data::Dumper; my @array1= ( {a=>1,b=>2,c=>3,d=>4}, {w=>0,x=>1,y=>2,z=>3} ); my @array1= ( {a=>1,b=>2,c=>3,d=>4}, {w=>0,x=>4,y=>2,z=>3} ); my @diff; foreach my $i ( 0..$#array1 ) { foreach my $key ( keys %{$array1[$i]} ) { if( $array1[$i]->{$key} ne $array2[$i]->{$key} ) { $diff[$i]= { %{$array1[$i]} }; $diff[$i]->{CHANGED}= delete $diff[$i]->{$key}; last; } } } print Dumper( \@diff );

The $diff[$i]= { %{$array1[$i]} }; bit copies the entire anonymous hash into a new anonymous hash and stores a reference to it into @diff.

The $diff[$i]->{CHANGED}= delete $diff[$i]->{$key}; bit deletes the changed key and the delete operator returns the associated value so that you can associate with the new key, "CHANGED".

This code prints out:

$VAR1 = [ undef, { 'w' => 0, 'CHANGED' => 1, 'y' => 2, 'z' => 3 } ];

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Changing the keys of hashes in arrays by tye
in thread Changing the keys of hashes in arrays by eclecticIO

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.