Grep 在 Perl 数组中查找项目
每次我输入一些内容时,代码总是告诉我它存在。但我知道有些输入不存在。怎么了?
#!/usr/bin/perl
@array = <>;
print "Enter the word you what to match\n";
chomp($match = <STDIN>);
if (grep($match, @array)) {
print "found it\n";
}
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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您提供给 grep 的第一个参数需要评估为 true 或 false 以指示是否存在匹配。所以应该是这样的:
如果您需要匹配许多不同的值,那么您也可能值得考虑将数组数据放入哈希值中,因为哈希值允许您有效地完成此操作,而无需遍历列表。
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:
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 ahash
, since hashes allow you to do this efficiently without having to iterate through the list.您似乎像 Unix
grep
实用程序一样使用grep()
,这是错误的。Perl 的
grep()
在标量上下文中计算每个表达式的值列表的元素并返回表达式为 true 的次数。因此,当
$match
包含任何“true”值时,标量上下文中的grep($match, @array)
将始终返回@array< 中的元素数量/代码>。
相反,尝试使用模式匹配运算符:
You seem to be using
grep()
like the Unixgrep
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:
这可以使用 List::Util 的
first
函数:List::Util
中的其他函数,例如max
、min
、sum
等可能对你有用This could be done using List::Util's
first
function:Other functions from
List::Util
likemax
,min
,sum
also may be useful for you除了 eugene 和 stevenl 发布的内容之外,您可能会遇到在一个脚本中同时使用
<>
和
的问题: 迭代(=连接)作为命令行参数给出的所有文件。但是,如果用户忘记在命令行上指定文件,它将从 STDIN 读取,并且您的代码将永远等待输入
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
我可能会发生这样的情况:如果您的数组包含字符串“hello”,并且如果您正在搜索“he”,则 grep 返回 true,尽管“he”可能不是数组元素。
也许,
if (grep(/^$match$/, @array)) 更合适。
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.您还可以检查多个数组中的单个值,例如,
You can also check single value in multiple arrays like,