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

Re: comparing two array

by citromatik (Curate)
on Jun 17, 2009 at 12:21 UTC ( #772362=note: print w/ replies, xml ) Need Help??

in reply to comparing two array

This is a faq: How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

If what you want is to see if a scalar is in the array, you can try grep:

print +(grep {$_ eq $elem} @array) ? "Yes" : "No";


my %h = map { $_ => 1 } @array; print defined $h{$elem} ? "Yes" : "No";

Update: Changed the grep regexp by eq (see the comment below from davorg)


Comment on Re: comparing two array
Select or Download Code
Replies are listed 'Best First'.
Re^2: comparing two array
by davorg (Chancellor) on Jun 17, 2009 at 13:29 UTC
    print +(grep {/$elem/} @array) ? "Yes" : "No";
    $ cat ./arr #!/usr/bin/perl my @arr = (100 .. 110); my $elem = 11; print +(grep { /$elem/ } @arr) ? 'Yes' : 'No'; $ ./arr Yes$

    Hmm... You might want to reconsider your idea of equality :-)


    See the Copyright notice on my home node.

    Perl training courses

Re^2: comparing two array
by Crian (Chaplain) on Jun 17, 2009 at 12:37 UTC

    Shouldn't it be

    print exists $h{$elem} ? "Yes" : "No";
    the second example?

      Considering all the values in %h are 1, it doesn't make any difference whether you use exists $h{$elem}, defined $h{$elem} or $h{$elem}.

      In this case...

      print defined $h{$elem} ? "Yes" : "No"; print exists $h{$elem} ? "Yes" : "No"; print $h{$elem} ? "Yes" : "No";

      Are all equivalent (give the same result). exists returns true if the specified element in the hash has ever been initialized, even if its current value is undefined. In this case, all elements has been initialized to 1. If you undefine one element of the hash, for example undef $h{$elem}, then $h{$elem} still exists, but its value is undef


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://772362]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2015-11-25 01:58 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (667 votes), past polls