Re: Compare two array's

From: John W. Krahn (krahnj_at_acm.org)
Date: 01/07/04


To: beginners@perl.org
Date: Wed, 07 Jan 2004 02:17:18 -0800

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


Relevant Pages

  • Re: random array elements and speed
    ... JJ> than splice for large arrays but slower for small arrays. ... and swap/pop is several perl ops. ... a loop with a list of sizes and use my code changes (you want to compare ...
    (comp.lang.perl.misc)
  • Re: Useless use of array element in void context
    ... of array element in void context". ... concentrated excerpt of my larger perl project. ... If you want to compare two arrays for equality of their elements, ...
    (comp.lang.perl.misc)
  • Re: Idiom for array index that Im foreaching over?
    ... >>you'll find that you rarely want to loop over an index. ... With hashes, indexed access, and hence loops ... > simplicity and elegance that I expect out of good modern Perl ... If, for some reason, the data is given in individual arrays, there are ...
    (comp.lang.perl.misc)
  • Re: Fw: question
    ... As a matter of fact Perl has: ... With the above functions and arrays and hashes there are very few data ... Also, PHP is a very different language then Perl, remember that. ... What happens if I add or remove keys from a hash while iterating over it? ...
    (perl.beginners)
  • Re: combining hashes
    ... in c they are much slower than arrays since you need to do ... The difference is that, unlike Perl, C doesn't have ... please don't tell me how to do searching in c. i was doing that in PL/I ... c's arrays are vs all string lookups. ...
    (comp.lang.perl.misc)