Grep在Perl数组中查找项目

jen*_*lee 16 perl grep

每当我输入内容时,代码总是告诉我它存在.但我知道有些输入不存在.怎么了?

#!/usr/bin/perl

@array = <>;
print "Enter the word you what to match\n";
chomp($match = <STDIN>);

if (grep($match, @array)) {
    print "found it\n";
}
Run Code Online (Sandbox Code Playgroud)

ste*_*enl 30

您给grep的第一个arg需要评估为true或false以指示是否存在匹配.所以它应该是:

# 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";
}
Run Code Online (Sandbox Code Playgroud)

如果您需要匹配许多不同的值,那么您可能还需要考虑将array数据放入a中hash,因为哈希允许您有效地执行此操作而无需遍历列表.

# 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";
}
Run Code Online (Sandbox Code Playgroud)


Eug*_*ash 27

您似乎使用的grep()是Unix grep实用程序,这是错误的.

grep()标量上下文中的Perl 评估列表中每个元素的表达式,并返回表达式为真的次数.因此,当$match包含任何"true"值时,grep($match, @array)在标量上下文中将始终返回元素的数量@array.

相反,尝试使用模式匹配运算符:

if (grep /$match/, @array) {
    print "found it\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 如果没有模式上的锚点,即 `(grep /^$match$/, @array)`,在 `(12)` 数组中搜索 `$match = 1` 将返回 true,而您可能期望返回 false ,因为“1”恰好是“12”的子串 (2认同)