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 = <&g
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";
}
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
You can also check single value in multiple arrays like,
if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
print "found it\n";
}
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";
}
This could be done using List::Util's first
function:
use List::Util qw/first/;
my @array = qw/foo bar baz/;
print first { $_ eq 'bar' } @array;
Other functions from List::Util
like max
, min
, sum
also may be useful for you
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.