Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep to find item in Perl array

Tags:

grep

perl

Every time I input something the code always tells me that it exists. But I know some of the inputs do not exist. What is wrong?

#!/usr/bin/perl

@array = <>;
print "Enter the word you what to match\n";
chomp($match = <STDIN>);

if (grep($match, @array)) {
    print "found it\n";
}
like image 806
jenglee Avatar asked Oct 26 '11 03:10

jenglee


People also ask

How do I grep an element in an array in Perl?

The Perl grep() function is a filter that runs a regular expression on each element of an array and returns only the elements that evaluate as true. Using regular expressions can be extremely powerful and complex. The grep() functions uses the syntax @List = grep(Expression, @array).

How do I search for an element in an array in Perl?

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

How do I grep multiple strings in Perl?

Grep Multiple Patterns To search for multiple patterns, use the OR (alternation) operator. The alternation operator | (pipe) allows you to specify different possible matches that can be literal strings or expression sets. This operator has the lowest precedence of all regular expression operators.


2 Answers

The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:

# note that grep returns a list, so $matched needs to be in brackets to get the 
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
    print "found it: $matched\n";
}

If you need to match on a lot of different values, it might also be worth for you to consider putting the array data into a hash, since hashes allow you to do this efficiently without having to iterate through the list.

# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;

# check if the hash contains $match
if (defined $hash{$match}) {
    print "found it\n";
}
like image 68
stevenl Avatar answered Sep 23 '22 16:09

stevenl


You seem to be using grep() like the Unix grep utility, which is wrong.

Perl's grep() in scalar context evaluates the expression for each element of a list and returns the number of times the expression was true. So when $match contains any "true" value, grep($match, @array) in scalar context will always return the number of elements in @array.

Instead, try using the pattern matching operator:

if (grep /$match/, @array) {
    print "found it\n";
}
like image 35
Eugene Yarmash Avatar answered Sep 23 '22 16:09

Eugene Yarmash