我如何在Perl中实现Unix grep? [英] How can I implement Unix grep in Perl?

查看:94
本文介绍了我如何在Perl中实现Unix grep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Perl中实现Unix的 grep ?我试图使用Perl的内置 grep 。这是不工作的代码:

  $ pattern = @ARGV [0]; 
$ file = @ARGV [1];

打开($ fp,$ file);

@arr =< $ fp>;

@lines = grep $ pattern,@arr;

close($ fp);
print @lines;

顺便说一句,我只尝试基本的 grep 功能不全功能,其次我不想自己做字符串解析。我想使用内置的 grep 或Perl的一些函数。



感谢您提前致谢:

解决方案

在Perl中引用整个数组,我们使用 @ 。但是要引用单个元素,它们是标量,我们使用 $

所以,您需要使用 $ ,而不是 @

  $ pattern = @ARGV [0]; 
$ file = @ARGV [1];

另外

  @lines = grep $ pattern,@arr; 

应该是

  @lines = grep / $ pattern /,@arr; 

grep 具有以下通用语法:

  grep EXPR,LIST 

它为 EXPR 评估 LIST 并返回由表达式评估为true的元素组成的列表值。

EXPR 在你的情况下是在数组 @arr 中搜索模式 $ pattern 。要搜索,您需要使用 / PATTERN / 而不使用 / 字符串 $ pattern 将被评估为真或假。

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;

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.

Thanks in advance :)

解决方案

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];

Also

this

@lines = grep $pattern, @arr;

should be

@lines = grep /$pattern/, @arr;

the grep in Perl has the general syntax of:

grep EXPR,LIST

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆