加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl中grep的用法:

发布时间:2020-12-16 00:39:33 所属栏目:大数据 来源:网络整理
导读:主要缘由是今天看代码的时候看到了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

主要缘由是今天看代码的时候看到了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','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风格

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读