Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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";

Or

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

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

citromatik


Comment on Re: comparing two array
Select or Download Code
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

      citromatik

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2014-07-31 02:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (244 votes), past polls