Jerry Preston wrote:
>
> I know that this is a no brainer, but I cannot not get it!  I want to
> compare two arrays and delete the same values in one array.
>
> foreach $j ( @a1 ) {
>   foreach $p ( @a2 ) {
>     $a2[ $p ] = undef  if $a1[ $j ] == $a2 $p ];
>   }
> }
>
> What is wrong and is there a better, PERL way to do this?

The first thing that's wrong is you're not starting with

  use strict;
  use warnings;

Your code doesn't work because you're iterating over the
values in the arrays instead of the indices. This will
work as you intended

  foreach my $j (0 .. $#a1) {
    foreach my $p (0 .. $#a2) {
      $a2[$p] = undef if $a1[$j] == $a2[$p];
    }
  }

but you'll get warnings when undefined elements of
@a2 are being compared.

The Perl way to do it is to build a hash of the elements
of @a1 like this

  my %a1 = map(($_, 1), @a1);
  foreach (@a2) { $_ = undef if $a1{$_} };

HTH,

Rob



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to