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";
}
This could be done using List::Util's
first
function:Other functions from
List::Util
likemax
,min
,sum
also may be useful for youYou can also check single value in multiple arrays like,
In addition to what eugene and stevenl posted, you might encounter problems with using both
<>
and<STDIN>
in one script:<>
iterates through (=concatenating) all files given as command line arguments.However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input
I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.
Perhaps,
if (grep(/^$match$/, @array))
more apt.You seem to be using
grep()
like the Unixgrep
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:
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:
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 ahash
, since hashes allow you to do this efficiently without having to iterate through the list.