Perl search in array

This Perl example is a function where I search for an element in an array, it returns the position or -1 if nothing matches.

#!/usr/bin/perl
use strict;
#tes tdata
my @arr = (2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14);
#read
print "Value:";
my $input = <>;
#test
print "position:".position(@arr,$input).$/;
#returns position or -1
sub position {
    for(0..($#_-1)){
        return $_ if($_[$_] == $_[$#_]);
    }
    return(-1);
}

As result we get for 9 -> 3 and for 4 -> -1 seems good.

sh-4.2# perl main.pl
Value:9 
position:3 
sh-4.2# perl main.pl 
Value:4     
position:-1  
sh-4.2#

4 thoughts on “Perl search in array”

  1. Right here is the right website for everyone who wishes to find
    out about this topic. You know a whole lot its almost hard to argue with you
    (not that I actually will need to…HaHa). You certainly put a brand new spin on a subject that has been discussed for years.
    Great stuff, just great!

Leave a Reply

Your email address will not be published.

3 × three =