You should be more careful with your assertions:

@a1 = qw(1 2 2 3); @a2 = qw(1 2 3 3);

Your code will consider @a1 and @a2 as equal when they clearly aren't. Your solution can only work when all array elements are unique and the order of elements is irrelevant. The original poster possibly wants an unordered comparision, but the problem with multiple identical elements remains.

If you modify your code to use the hash as a counter, then it works better:

use strict; sub dec($) { $_[0] ? $_[0]-- : 0 }; my @a1 = qw(1 2 2 3); my @a2 = qw(1 2 3 3); my %a1; $a1{$_}++ for (@a1); my @only_a2 = map { dec $a1{$_} ? () : $_ } @a2; print "Only in \@a2 : @only_a2\n";

In the end, I guess what the poster really wants is what's called the symmetric difference between two sets, which is what you (for example) get by building @only_a1 and @only_a2.


In reply to Re: Re: How do I compare two arrays? by Corion
in thread How do I compare two arrays? by luoina

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.