Re: Compare two array's

2004-01-07 Thread Rob Dixon
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]
 




Re: Compare two array's

2004-01-07 Thread John W. Krahn
Jerry Preston wrote:
> 
> Hi!,

Hello,

> 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?

No, but there is a Perl way to do it:   :-)

@a2 = do {
my %seen;
@seen{ @a1 } = ( 1 ) x @a1;
grep !$seen{ $_ }, @a2;
};



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Compare two array's

2004-01-07 Thread Jan Eden
Maybe the missing opening bracket on the third line?

>$a2[$p] = undef  if $a1[$j] == $a2[$p];

Being a beginner myself, I cannot recommend a better way.

- Jan

Jerry Preston wrote:

>Hi!,
>
>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?
-- 
There are 10 kinds of people:  those who understand binary, and those who don't

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Compare two array's

2004-01-07 Thread Jerry Preston
Hi!,

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?

Thanks,

Jerry