in reply to Difference between two arrays

use strict; use warnings; my $before = [qw(1 2 3 4 5 6 7 8 9 10)]; my $after = [qw(1 2 3 4 6 7 5 8 9 10)]; # Find the first and last that are out of position my ($lo_1, $hi_1); for (0..$#$before) { if ($before->[$_] != $after->[$_]) { (defined $lo_1 ? $hi_1 : $lo_1) = $_; } } # If the first item is out of order relative to the one following it, # it has been moved from higher up; otherwise, the move was in the oth +er direction if ($after->[$lo_1+1] < $after->[$lo_1]) { print "Moved element $hi_1 to $lo_1\n"; } else { print "Moved element $lo_1 to $hi_1\n"; }

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Difference between two arrays
by rafl (Friar) on Mar 23, 2006 at 02:12 UTC

    Thanks for your solution. It's pretty much what I was looking for. :-)

    But.. are you sure if that code works for any input data one could think of? Couldn't the

    $after->[$lo_1 + 1]

    result in an undefined value when $lo_1 equals $#{$after}?

    Cheers, Flo

      $lo_1 would never be the last index in the array, so no.

      The highest order change is either moving element index 8 to 9 or moving 9 to 8. In either case $lo_1 will be 8, and $lo_1 + 1 will be 9, and in range.

      I think the above is the best solution here.

      ---
      my name's not Keith, and I'm not reasonable.