From PHP to Perl


Is In Array?

Posted in Programming by assasiner on the December 3, 2006

I was searching if there was a function like in_array of PHP in Perl, but there is not such function, but, it is still very easy to check!
This was useful for me so i hope it is for you
In PHP:

<?php
$string = ‘fin_helm’;
$array = array(‘full_plate’,'manteau’,'boots’,'two_handed_sword’,'fin_helm’);
if(in_array($string, $array))
{
print “$string is in the array”;
}
?>

In Perl:

#!/usr/bin/perl
my $string = ‘fin_helm’;
my @array = qw/full_plate manteau boots two_handed_sword fin_helm/;
if(grep $_ eq $string, @array)
{
print “$string is in the array”;
}

So, those codes do exactly the same.
If you don’t know much perl you will be wondering what does the grep function, the grep function examines each of an element of an array (represented with $_) and then we make a comparison or something with it, in this case $_ eq $string, grep, returns the elements with where true, in this case we are not requesting the elements, we are requesting a sacalar value, so, in perl 0 is false, and every other number is true, that will return 1, so its true, and the element is in the array :)
I hope you all find this useful, bye

29 Responses to 'Is In Array?'

Subscribe to comments with RSS or TrackBack to 'Is In Array?'.

  1. norev said,

    Found this useful, cheers.

  2. Eric said,

    This helped a lot for me coming from PHP.

  3. BluesRocker said,

    Thanks a lot.

  4. Andy said,

    Thanks – this helped me as a Perl programmer learning PHP.

    BTW, if you are just searching for a string in the array, you could slightly simplify the Perl by replacing
    if(grep $_ eq $string, @array)
    with
    if(grep /$string/, @array)

  5. MMM said,

    Great, exactly what I was looking for… helped me a lot when digging out perl code and need to extend it.

  6. Patrick said,

    Thanks for this! I’ve used grep before, but I didn’t think of it used like this.

    In response to Andy:

    grep /$string/, @array

    uses regular expressions, which is perfect if you need the full complexity of searching the array against a regular expression pattern. If you are only searching for a string in the array,

    grep ($_ eq $string, @array)

    is much faster and CPU friendly.

  7. Giancarlo said,

    One question… if I have an array of hashes, this routine can be usefull as well? How should I use it?

    For example:

    $array = [ {id=>1,name=>'aaa'},
    {id=>2,name=>'bbb'},
    {id=>3,name=>'ccc'},
    ]

    How should I wirte the routine to find inside the array the id=>2 using the grep?

    TIA

  8. assasiner said,

    #!/usr/bin/perl
    use strict;

    my @array = ({id=>’1′,name=>’aaa’},{id=>’2′,name=>’bbb’},{id=>’3′,name=>’ccc’});

    if(grep{ $$_{‘id’} eq ‘2′ } @array)
    {
    print ‘I found 2′;
    }

  9. Giancarlo said,

    Thnx a lot.

  10. assasiner said,

    no problem :]

  11. Giancarlo said,

    Sorry to bother you more… I got how to use it but… if I want to retrieve the complete hash when the grep founds the occurrence… how do I assign it to a variable?

    TIA

  12. assasiner said,

    if(grep{ $$_{’id’} eq ‘2′ } @array)
    {
    print ‘My id is: ‘.$$_{‘id’}.’ and my name is ‘.$$_{‘name’];
    }

    that should work :]

  13. Giancarlo said,

    ok i’ll try it and let you know how well it was :)

    And Thnx again.

  14. Giancarlo said,

    Ok this is my new problem now… each element in the array is a hash. I know with that if that I can access to any element inside the hash that is found. but how can I have access to the complete hash as a whole.

    Is that posible? I’ve tried with $$_ or $_ but those are not working to give me the complete hash.

  15. assasiner said,

    I think $_ is a reference to the hash… But apart from $_ and $$_ i dont know really, im sorry i dont know much perl hehe i’m still learning, slow but learning :P

  16. Jz said,

    Found this very handy, ty. One thing I found was grep is a regex based function, so if you’re not careful it will match things you might think it shouldn’t.

    eg
    my @haystack = (‘fifteen’,'fish’);
    my $needle = ‘fi.’;
    my $result = grep(/$needle/,@haystack);

    At this point $result will equal 2, because the regex ‘fi.’ matches both of the elements. You need to escape the needle before you test it.

    sub in_array {
    my $needle = shift(@_); # needle is the first argument
    $needle =~ s/([^0-9a-zA-Z])/\\$1/g; #swap anything that could need escaping to escaped form
    if(grep(/$needle/,@_)>0){return 1;} # check the array
    return 0; # else it didn’t match.
    }

  17. Gomorrah said,

    Somehow i missed the point. Probably lost in translation :) Anyway … nice blog to visit.

    cheers, Gomorrah!

  18. Matt said,

    Still handy. :-D


  19. [...] was looking for this useful function I always use in php and found this simple article. Basically, the function that permit you to do that is grep used in this way: my $string = [...]

  20. Petter said,

    Very useful, thanks a lot! This was surprisingly hard to find for being such a basic trick.. Cheers

  21. Tom said,

    Thanks a lot!

  22. willie said,

    worked great! thanks :]

  23. flies said,

    regarding andy’s post:


    BTW, if you are just searching for a string in the array, you could slightly simplify the Perl by replacing
    if(grep $_ eq $string, @array)
    with
    if(grep /$string/, @array)

    please note that the second line will match $string to _substrings_ of @array elements, eg $string=12 matches @array=(“september 12th”) as well as @array=(12).

  24. Dave said,

    Check cpan
    http://search.cpan.org/~vparseval/List-MoreUtils-0.22/lib/List/MoreUtils.pm

    use List::MoreUtils(qw);

    if( any{$_ eq $string} @array)
    {
    print “$string is in the array”;
    }

  25. ibrahim said,

    hello , am biggener in perl can you help me in this array:
    @array=();
    print “enter (1) to determine the length of array\n”;
    print “enter (2) to enter the element of array\n”;
    print “enter (3) to find zeroes\n”;
    print “enter (4) to find the max\n”;
    print “enter (5)to find the even number\n”;
    print “enter (6) to find the sum of odd number\n”;
    print “enter (7) to find the prime numbers\n”;
    print “enter (8) to to add to array \n”;
    print “enter (9) to sort array descending \n”;
    print “enter (10) to creat associated array\n”;
    print “enter (11) to print a key & values of associated array\n”;
    print “enter (12) t0 exit \n”;

    please ..

  26. Rick Stock said,

    Thanks – just what I was looking for :-)

  27. manu said,

    Thaks for posting this, it’s a great option.

  28. tomn9 said,

    Thanks, very helpfull


Leave a Reply