coeus_wang has asked for the wisdom of the Perl Monks concerning the following question:

Hi Dear all, I have two strings like below: @a = qw('a', 'b', 'c'} @b = qw('a', 'a', 'b', 'c', 'd', 'd') for @b, 'a' and 'd' are both duplicated. I want compare if all the elements in @a are all belong to @b, also return the element in @b which not show in @a. for example, to compare these two array, i want to get a value like this: @c = ('d'). Please help! Thanks a lot. Coeus
  • Comment on How to compare two arrays under certain conditions?

Replies are listed 'Best First'.
Re: How to compare two arrays under certain conditions?
by Fletch (Bishop) on Sep 19, 2008 at 18:07 UTC

    Look for "How do I compute the difference of two arrays? How do I compute the intersection of two arrays?" in perlfaq4. And use <code></code> tags in the future to make your questions more readable.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: How to compare two arrays under certain conditions?
by jethro (Monsignor) on Sep 19, 2008 at 18:30 UTC

    The code in perlfaq4 sadly assumes no duplicates. But nonetheless hashes are the solution:

    foreach @b { $hb{$_}++ } foreach @a { $ha{$_}++ } foreach keys %hb { push @c,$_ if ( not exists $ha{$_} ); }

    This code should be easier to grok than the dense code in the perlfaq. Because %hb is a hash, "keys %hb" is identical to @b without the duplicates. In the loop a value gets pushed into @c if it is not in %ha and so also not in @a.

    You might be able now to create a second loop that finds "all the elements in @a are all belong to @b".

Re: How to compare two arrays under certain conditions?
by eff_i_g (Curate) on Sep 19, 2008 at 19:10 UTC