Grep to find item in Perl array

后端 未结 6 2058
名媛妹妹
名媛妹妹 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条回答
  •  死守一世寂寞
    2021-02-04 04:26

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

提交回复
热议问题