Grep to find item in Perl array

2020-05-25 17:45发布

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";
}

标签: perl grep
6条回答
仙女界的扛把子
2楼-- · 2020-05-25 18:03

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

查看更多
一夜七次
3楼-- · 2020-05-25 18:06

You can also check single value in multiple arrays like,

if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
    print "found it\n";
}
查看更多
一纸荒年 Trace。
4楼-- · 2020-05-25 18:13

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

查看更多
混吃等死
5楼-- · 2020-05-25 18:24

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.

查看更多
Lonely孤独者°
6楼-- · 2020-05-25 18:25

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";
}
查看更多
劳资没心,怎么记你
7楼-- · 2020-05-25 18:27

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";
}
查看更多
登录 后发表回答