in reply to comparing arrays

When this happens, I simply want to remove one copy of the pair and keep the other (remove one element from each array)

You don't explain which array the element should be removed from. In your example, you show one of a set of duplicates being removed from the first array and one from the other set of duplicates being removed from the other array. Could they always be removed from the same array? Do you wish to switch off and remove from first one, then the other, then the first, etc.?

Once you figure that out, it should be pretty easy to do. Hint: use a hash (or two if necessary.) The keys of a hash are unique.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^2: comparing arrays
by Anonymous Monk on Dec 16, 2004 at 01:17 UTC
    Hi, Sorry I thought I had explained it. I want to remove just one copy of the duplicate pair e.g. one value from each array - it doesn't matter which array the values are removed from. I dont see how a hash would work - it would help extract the unique values in each array, but how could I use it to keep one copy of the duplicate values? Thanks!
      it doesn't matter which array the values are removed from.

      In that case, it is very simple. You iterate over one array and rebuild it. If a value shows up in the second array, you just ignore it as you are rebuilding. Use a hash to store the values so that lookup is fast...

      my @array1 = (1, 2, 3, 4, 5); my @array2 = (2, 4, 6, 8, 10); my %hash = map {$_=>1} @array2; @array1 = grep { not exists $hash{$_} } @array1; print "@array1\n";

      -sauoq
      "My two cents aren't worth a dime.";
      

        A hash slice would (I guess) be more efficient (insted of the map-statement).

        my %hash; @hash{@array2};

        This code will set for all the elements in @array2 the value in the hash to undef. And later on you can see if it exists by using the exists (or not exists) function (as done in your code).