Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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)


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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2018-03-17 21:11 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (226 votes). Check out past polls.