in reply to Array searching

I think this might meet your specs:

Updated -- added last; statement in loop
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array1 = (1,2,3); my @array2 = (1,2,3,4,5); my %hash = map { $_ => 1 } @array1; my %hash2 = map { $_ => 1 } @array2; print "Before:\n" . Dumper(\%hash) . Dumper(\%hash2); # remove the unwanted "value" my $to_delete = 2; my $old = delete($hash{$to_delete}); my $old2 = delete($hash2{$to_delete}); for my $x (keys %hash2) { next if exists($hash{$x}); $hash{$x} = 1; delete($hash2{$x}); last; # updated -- added this line } print "After:\n" . Dumper(\%hash) . Dumper(\%hash2); __OUTPUT__ Before: $VAR1 = { '1' => 1, '3' => 1, '2' => 1 }; $VAR1 = { '4' => 1, '1' => 1, '3' => 1, '2' => 1, '5' => 1 }; After: $VAR1 = { '4' => 1, '1' => 1, '3' => 1, }; $VAR1 = { '1' => 1, '3' => 1, '5' => 1, };


Where do you want *them* to go today?

Replies are listed 'Best First'.
Re^2: Array searching
by GrandFather (Saint) on Apr 13, 2007 at 00:14 UTC

    Umm, no. OP wrote "... and replace it with a number from the second array with out duplicating numbers in the first array".

    It's not clear if OP intended to add a new element to the first array or replace the deleted element's value. That is, it's not clear if the ordering of the array is important of not, but it is clear that the first array should get a new element from the second array that doesn't already exist in the first array.


    DWIM is Perl's answer to Gödel

      I spoke with OP in CB and he stated that order was *not* important, and that duplication was not allowed.

      Based upon this additional info, I solved the task using hashes.


      Where do you want *them* to go today?
        Thanks so much!