(如果你是个Perl的新手,你可以先跳过下面的两段,直接到 Grep vs.loops 样例这一部分,放心,在后面你还会遇到它)
<pre> grep BLOCK LIST grep EXPR, LIST </pre>
请避免在 BLOCK 或 EXPR 块中修改 $_ ,因为这会相应的修改 LIST 中元素的值。同时还要避免把 grep 返回的列表做为左值使用,因为这也会修改 LIST 中的元素。(所谓左值变量就是一个在赋值表达式左边的变量)。一些 Perl hackers 可能会利用这个所谓的”特性”,但是我建议你不要使用这种混乱的编程风格.
grep 与循环
这个例子打印出 myfile 这个文件中含有 terriosm 和 nuclear 的行(大小写不敏感).
open FILE "<myfile" or die "Can't open myfile: $!";
print grep /terrorism|nuclear/i, <FILE>;
while ($line = <FILE>) {
if ($line =~ /terrorism|nuclear/i) { print $line }
}
计算数组中匹配给定模式的元素个数
在一个标量上下文中,grep 返回的是匹配的元素个数.
$num_apple = grep /^apple$/i, @fruits;
输出列表中的不同元素
@unique = grep { ++$count{$_} < 2 }
qw(a b a c d d e f g f h h);
print "@unique\n";
输出结果: a b c d e f g h$count{$_} 是 Perl 散列中的一个元素,是一个键值对 ( Perl中的散列和计算机科学中的哈希表有关系,但不完全相同) 这里 count 散列的键就是输入列表中的各个值,而各键对应的值就是该键是否使 BLOCK 估值为真的次数。当一个值第一次出现的时候 BLOCK 的值被估为真(因为小于2),当该值再次出现的时候就会被估计为假(因为等于或大于2)。
取出列表中出现两次的值
@crops = qw(wheat corn barley rice corn soybean hay
alfalfa rice hay beets corn hay);
@duplicates = grep { $count{$_} == 2 }
grep { ++$count{$_} > 1 } @crops;
print "@duplicates\n";
列出当前目录中的文本文件
@files = grep { -f and -T } glob '* .*';
print "@files\n";* 表示匹配所以当前目录下不以 . 开头的文件, .* 表示匹配当前目录下以 . 开头的所有文件。 -f 和 -T 文件测试符分别用来测试纯文件和文本文件,是的话则返回真。使用 -f and -T 进行测试比单用 -T 进行测试有效,因为如果一个文件没有通过 -f 测试,那么相比 -f 更耗时的 -T 测试就不会进行。
从数组中选出非重复元素
@array = qw(To be or not to be that is the question);
print "@array\n";
@found_words =
grep { $_ =~ /b|o/i and ++$counts{$_} < 2; } @array;
print "@found_words\n";
输出结果:
To be or not to be that is the question
To be or not to question
逻辑表达式 $_ =~ /b|o/i 匹配包含有 b 或 o 的元素(不区别大小写)。在这个例子里把匹配操作放在累加前比反过来做有效些。比如,如果左边的表达式是假的,那么右边的表达式子就不会被计算。
选出二维坐标数组中横坐标大于纵坐标的元素
# An array of references to anonymous arrays
@data_points = ( [ 5, 12 ], [ 20, -3 ],
[ 2, 2 ], [ 13, 20 ] );
@y_gt_x = grep { $_->[0] < $_->[1] } @data_points;
foreach $xy (@y_gt_x) { print "$xy->[0], $xy->[1]\n" }
输出结果:
5, 12
13, 20
在一个简单数据库中查找餐馆
这个例子里的数据库实现方法不是实际应用中该使用的,但是它说明了使用 grep 函数的时候,只要你的内存够用, BLOCK 块的复杂度基本没有限制。
# @database is array of references to anonymous hashes





