Perl中grep的用法:

主要缘由是今天看代码的时候看到了grep,自己不是很熟悉,学习下

先看grep中的文档:
    * grep BLOCK LIST

    * grep EXPR,LIST

      This is similar in spirit to, but not the same as, grep(1) and its relatives. In particular, it is not limited to using regular expressions.

      Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.

         1. @foo = grep(!/^#/, @bar); # weed out comments

      or equivalently,

         1. @foo = grep {!/^#/} @bar; # weed out comments

      Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Similarly, grep returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by grep (for example, in a foreach , map or another grep) actually modifies the element in the original list. This is usually something to be avoided when writing clear code.

      If $_ is lexical in the scope where the grep appears (because it has been declared with my $_ ) then, in addition to being locally aliased to the list elements, $_ keeps being lexical inside the block; i.e., it can't be seen from the outside, avoiding any potential side-effects.

举个例子:
            if (grep {$_ eq $fragment} @data){
               print "$makefile excluded/n";
            }

@test=('apple','veers','cat','fdf');
$num_apple = grep /^apple$/i, @test;
print $num_apple."*************";


@test=('apple','veers','cat','fdf');
@num_apple = grep {/^apple/} @test;
print $num_apple[0]."*************";

以上两个例子是有区别的,一个是grep表达式后面有逗号,并且没有大括号,而后者没有,前者是数字,后者输出数组


不用grep也可以用loop达到同样的效果:

open FILE "<myfile" or die "Can't open myfile: $!";
print grep /apple/i, <FILE>;;

代替方式使用loop(循环)来完成:
while ($line = <FILE>;) {
if ($line =~ /apple/i) { print $line }
}

前者对于大文件效率不高而后者更适合C风格

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值