Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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!

Replies are listed 'Best First'.
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";

      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

      Right on fisher! Thanks!

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://878178]
Approved by rovf
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-03-20 03:13 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (247 votes). Check out past polls.