Saturday, April 9, 2011

IN_ARRAY sub function in PERL

IN_ARRAY is one of the common functionality in PHP that searches data in an array - http://php.net/in_array. This function takes 2 parameters: (1) the search key and (2) the array stack, it returns boolean whether found or not.

This functionality lacks in Perl and with this post, we can now have it in Perl.

The function below follows the same parameters we set in PHP: in_array(<search key>, <array>). This function map the array into hash in which Perl can do searches and returns 1 or 0.

Hope you like it!! Enjoy!

sub in_array
{
     my ($search_key, @arr) = @_;

     my %items = map {$_ => 1} @arr;
     return (exists($items{$search_key})) ? 1 : 0;
}


Usage:

#!/usr/bin/perl

my @arr = ('Paul','Raf','Tina','Mich');

sub in_array
{
     my ($search_key, @arr) = @_;

     my %items = map {$_ => 1} @arr;
     return (exists($items{$search_key})) ? 1 : 0;
}

if (&in_array('Paul', @arr))
{
     print "Got you Paul!!\n";
}
else
{
     print "Paul not found!!\n";
}


1;


Output:

paulgonzaga:Perl paulgonzaga$ perl in_array.pl
Got you Paul!!
paulgonzaga:Perl paulgonzaga$

No comments:

Post a Comment