From PHP to Perl

Is In Array?

Posted in Programming by gosukiwi on 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

$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:

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


38 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)
    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’},

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


  8. assasiner said,

    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?


  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.

    • hiren said,


      • hiren said,


  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 πŸ˜›

  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.

    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. πŸ˜€

  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)
    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

    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:
    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

  29. JaysAPIDocs said,


    YOu rock…

    if(grep $_ eq $string, @array)


    The reverse

    if(!grep $_ eq $string, @array)

    Made my day…

    Such an easy way to calculate if a value is in an array…

    Everything should be this easy.

  30. BRPocock said,

    For what it’s worth:

    If you intend to search the array more than once, it’s actually faster to hash it.

    my @array = ( ‘a’ .. ‘z’ );
    my %hash = map { $_ => 1 } (@array);

    if ($hash{ $something }) { print “$something is in the array” }

    • GailH said,

      This is very good. I didn’t think about it this way.

  31. Ananda said,

    Thanks very useful!

  32. chonnikant said,

    How to code perl to php

    sub distinct{
    $size = 0;
    @arrays = @_;
    $size = @arrays;
    if($size > 0){
    if($_ eq $arrays[$step1]){ $exit = 1;}
    if($exit == 0 && $arrays[$step1] ne ""){
    $temps[$step2++] = $arrays[$step1];
    $size = @temps;
    return @temps;
    Help me. please

  33. A. User said,

    Thanks a lot!

  34. Droppen said,

    sub in_array {
    my ($string, $array) = @_;
    my $found = 0;
    foreach (@$array) {
    if ($_ == $string) {
    $found = 1;
    if ($found) {
    return 1;
    return 0;

    usage: in_array($string, \@array)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: