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

Grepping on array

by hotshot (Prior)
on May 19, 2004 at 12:54 UTC ( #354583=perlquestion: print w/replies, xml ) Need Help??

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

Hi all!

I have two arrays, I need to get all the values values in one array that DON'T appear in the second array, example:
my @arr1 = qw(a b c d e f g h); my @arr2 = qw(d a e); # needed array @result = qw(b c f g h);
Anyone?

Replies are listed 'Best First'.
Re: Grepping on array
by diotalevi (Canon) on May 19, 2004 at 13:01 UTC
    I would feel silly quoting the documentation. Execute perldoc -q "difference of two arrays" to see the standard answer. This is in perlfaq4, btw.
Re: Grepping on array
by ctilmes (Vicar) on May 19, 2004 at 13:05 UTC
    You can also use List::Compare to do this sort of thing:
    my @arr1 = qw(a b c d e f g h); my @arr2 = qw(d a e); my @result = List::Compare->new(\@arr1, \@arr2)->get_Lonly; # @result = qw(b c f g h);
Re: Grepping on array
by Abigail-II (Bishop) on May 19, 2004 at 13:01 UTC
Re: Grepping on array
by herveus (Parson) on May 19, 2004 at 13:08 UTC
    Howdy!

    my %first = map { $_ => 1 } @arr2; @result = grep !exists $first{$_}, @arr1;

    %first is a hash whose keys are the distinct values in @arr2. The grep returns a list of the values in @arr1 that don't exist in %first, thus eliminating values in @arr2.

    yours,
    Michael
Re: Grepping on array
by monkey_boy (Priest) on May 19, 2004 at 15:12 UTC

    Set::scalar
    esp. usefull if your manipulations get more complex.

    I should really do something about this apathy ... but i just cant be bothered
Re: Grepping on array
by dragonchild (Archbishop) on May 19, 2004 at 14:07 UTC
    This is a very basic set arithmetic question. (You're looking for the result set when subtracting @arr2 from @arr1.)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2023-03-20 22:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (59 votes). Check out past polls.

    Notices?