如何在 Perl 中实现 Unix grep? [英] How can I implement Unix grep in Perl?
问题描述
如何在 Perl 中实现 Unix 的 grep
?我尝试使用 Perl 的内置 grep
.这是不起作用的代码:
How can I implement grep
of Unix in Perl? I tried to use Perl's built-in grep
. Here is the code which is not working:
$pattern = @ARGV[0];
$file= @ARGV[1];
open($fp,$file);
@arr = <$fp>;
@lines = grep $pattern, @arr;
close($fp);
print @lines;
顺便说一下,我只尝试基本的 grep
功能而不是全功能,其次我不想自己进行字符串解析.我想使用内置的 grep
或 Perl 的一些功能.
And by the way, i am trying only basic grep
functionality not full featured and secondly i don't want to do string parsing myself. I want to use inbuilt grep
or some function of Perl.
提前致谢:)
推荐答案
在 Perl 中,我们使用 @
来引用整个数组.但是为了引用单个元素,我们使用$
.
In Perl to refer an entire array we use @
. But to refer the individual elements, which are scalar we use $
.
因此,您需要在这些行上使用 $
而不是 @
:
So, you need to use $
and not @
on these lines:
$pattern = @ARGV[0];
$file= @ARGV[1];
还有
这个
@lines = grep $pattern, @arr;
应该是
@lines = grep /$pattern/, @arr;
Perl 中的 grep 具有以下一般语法:
the grep in Perl has the general syntax of:
grep EXPR,LIST
它为 LIST
的每个元素计算 EXPR
并返回由那些表达式计算为真的元素组成的列表值.
It evaluates the EXPR
for each element of LIST
and returns the list value consisting of those elements for which the expression evaluated to true.
EXPR
在您的情况下正在数组 @arr
中搜索模式 $pattern
.要搜索,您需要使用 /PATTERN/
而不使用 /
字符串 $pattern
将被评估为真或假.
The EXPR
in your case is searching for the pattern $pattern
in array @arr
. To search you need to use the /PATTERN/
without the /
the string $pattern
will be evaluated for true or false.
这篇关于如何在 Perl 中实现 Unix grep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!