# Compare two array's

Ask a Question related to PERL Beginners, Design and Development.

1. ## Compare two array's

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

Jerry Preston Guest

2. ## Re: Compare two array's

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
Jan Eden Guest

3. ## Re: Compare two array's

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
John W. Krahn Guest

4. ## Re: Compare two array's

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

Rob Dixon Guest

#### Posting Permissions

• You may not post new threads
• You may post replies
• You may not post attachments
• You may not edit your posts