Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-24 06:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found