| Contents | Up | Previous | Next |
The grep function can be used to filter items out of an array based on a boolean expression or a regular expression. The syntax for the block usage is similar to map while the syntax for the regexp usage is similar to split.
Here is an example that takes a file and filters only the perl comments whose length is lesser than 80 characters:
|
And here's how grep can help us find the first 100 primes:
use strict;
my @primes = (2);
for(my $n=3 ; scalar(@primes) < 100 ; $n++)
{
if (scalar(grep { $n % $_ == 0 ; } @primes) == 0)
{
push @primes, $n;
}
}
print join(", ", @primes), "\n";
|
| Contents | Up | Previous | Next |