Grep to find item in Perl array

后端 未结 6 2069
名媛妹妹
名媛妹妹 2021-02-04 03:51

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         


        
6条回答
  •  猫巷女王i
    2021-02-04 04:09

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

提交回复
热议问题