in reply to comparing arrays

I got the same set of pairs left in the arrays as TedPride, but I found a problem with his code in that he is splicing from the front of the array and that makes the indexes further along wrong, I believe. The reason it worked OK with this data set is because the only duplicate pair to be spliced from the arrays is the last element. I got warnings when I moved the duplicate from the last pos. in the arrays to the next to the last. But for some reason, the data came out OK (but with the warnings)! I eliminated the warnings with

for (reverse 0..$#array1)

change to the for loop.

Ned's works but I don't know why indexing a higher number

$i++
after a splice doesn't cause problems as the array keeps getting resized with splice. Hope someone might know. A link from c.l.p.m.,
http://groups-beta.google.com/group/comp.lang.perl.misc/msg/49831a95770a2ee5
dicusses this and there were a few links in my Perl Monks search, which seemed to indicate counting backwards in the for loop.

My solution walked from the end of the array to the front, splicing when duplicate pairs were found.

#!/usr/bin/perl use strict; use warnings; my @a1 = qw(13470660 13471850 14028274 14028286); my @a2 = qw(14028145 14028286 13476691 13471850); my %hash; for (reverse 0..$#a1) { # Does 2 checks. To see if a number from the second array was # already seen in the first array. Also, checks to see if its # a 'reversal' or flip flop and thus a duplicate. if (exists $hash{$a2[$_]} && $hash{$a2[$_]} == $a1[$_]) { splice @a1, $_, 1; splice @a2, $_, 1; } else { $hash{$a1[$_]} = $a2[$_]; } } print "@a1\n@a2\n";
Chris

Replies are listed 'Best First'.
Re^2: comparing arrays
by nedals (Deacon) on Dec 17, 2004 at 06:55 UTC
    Ned's works but I don't know why indexing a higher number, $i++, after a splice doesn't cause problems as the array keeps getting resized with splice. Hope someone might know.

    The answer lies in the result..
    1 9 3 5 4 2
    3 2 1 6 7 9

    At i=0, the inner foreach loop takes out the first match set at index 0; and increments to 1.
    9 3 5 4 2
    2 1 6 7 9

    Then at i=4, instead of taking out the first match set it takes out the second.
    9 3 5 4
    2 1 6 7