CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
compare two arrays

 



perlchaser
Novice

Aug 30, 2012, 10:13 PM

Post #1 of 5 (1201 views)
compare two arrays Can't Post

I have two arrays. some of the elements in the two arrays are common to both, some are unique to each array. I want to compare the two arrays and find out the elements that are common in both arrays. how to do it?

Thank you,

Jackie


Laurent_R
Veteran / Moderator

Aug 30, 2012, 11:40 PM

Post #2 of 5 (1199 views)
Re: [perlchaser] compare two arrays [In reply to] Can't Post

To check for existence of elements, the right thing is generally to load one of the arrays is a hash.

However, it is probably better to use an existing module from CPAN such as List::Util or List::MoreUtils, which do the work for you.


Chris Charley
User

Aug 31, 2012, 3:57 AM

Post #3 of 5 (1190 views)
Re: [perlchaser] compare two arrays [In reply to] Can't Post

Here is the answer given in perldoc, (type perldoc -q intersection at your command prompt.

Code
 C:\Old_Data\perlp>perldoc -q intersection  
Found in C:\Perl64\lib\pods\perlfaq4.pod
How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each
element is unique in a given array:

@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}

Note that this is the *symmetric difference*, that is, all elements in
either A or in B but not in both. Think of it as an xor operation.


C:\Old_Data\perlp>

The module, List::Compare, will also do this for you.


(This post was edited by Chris Charley on Aug 31, 2012, 4:00 AM)


BillKSmith
Veteran

Aug 31, 2012, 6:17 AM

Post #4 of 5 (1184 views)
Re: [perlchaser] compare two arrays [In reply to] Can't Post

Refer to the FAQ: perldoc -q "How do I compute the difference of two arrays"
Good Luck,
Bill


perlchaser
Novice

Aug 31, 2012, 8:23 AM

Post #5 of 5 (1177 views)
Re: [Chris Charley] compare two arrays [In reply to] Can't Post

Thank all you guys for the code and comments. The code is working perfectly for me, and all the comments are very helpful! I appreciate!

In Reply To

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives