Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Array comparison using perl

by ajguitarmaniac (Sexton)
on Dec 21, 2010 at 07:56 UTC ( #878178=perlquestion: print w/ replies, xml ) Need Help??
ajguitarmaniac has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks! This one sounds real simple but for some reason I'm having a hell of a time figuring it out! Here goes.. I have 2 arrays, say

my @arr1 = ('1','2','3','4','5','6','7','8','9'); my @arr2 = ('1','4','5','9','7');

I need to pick out those elements that are found in @arr1 but not in @arr2 and store them into another array(say @arr3) and print the values consequently.It must be noted that elements in @arr2 will for sure exist in @arr1. Help me out Monks!

Comment on Array comparison using perl
Select or Download Code
Re: Array comparison using perl
by samarzone (Pilgrim) on Dec 21, 2010 at 08:20 UTC

    You will need to build some logic based on hashes, loops or may be grep. Submit your latest effort.

    -- Regards - Samar
Re: Array comparison using perl
by Khen1950fx (Canon) on Dec 21, 2010 at 08:37 UTC
    That's easy enough. Using List::Compare:
    #!/usr/bin/perl use strict; use warnings; use List::Compare; my @arr1 = (1, 2, 3, 4, 5, 6, 7, 8, 9); my @arr2 = (1, 4, 5, 9 ,7); my $lc = List::Compare->new(\@arr1, \@arr2); my @arr3 = $lc->get_unique; print "@arr3\n";

      Thanks Khen1950fx!

Re: Array comparison using perl
by fisher (Priest) on Dec 21, 2010 at 11:34 UTC
    ...and not using any modules:
    #!/usr/bin/env perl # use strict; use warnings; my @a1 = (1, 2, 3, 4, 5, 6, 7, 8, 9); my @a2 = (1, 4, 5, 9 ,7); print "\@a1 is (".(join ",", @a1).")\n"; print "\@a2 is (".(join ",", @a2).")\n"; my ($e1, $f); my @a3; for $e1 (@a1) { $f = 0; for (@a2) { if ($e1 eq $_) { $f++; } } unless ($f) { push @a3, $e1 } } print "\@a3 is (".(join ",", @a3).")\n";

      Right on fisher! Thanks!

      and what happens when the number of elements increases? This code is O(n2) which doesn't scale at all well. Better is something like:

      my %hits; ++$hits{$_} for @a1; my @matched = grep {exists $hits{$_}} @a2;
      True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://878178]
Approved by rovf
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2014-11-29 05:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (203 votes), past polls