Using the Perl grep() function
Introduction
The
grep function is used to filter lists. The basic syntax is @out = grep { CODE } @in;
where
CODE is some Perl code. For each element of @in, CODE is executed with $_ set to the element. If the code returns a true value, the element is placed in the output list; otherwise it is discarded.Example 1
Say you have a list of strings, and want to keep only those with less than 8 characters.
#!/usr/bin/perl
use strict;
use warnings;
my @strs = qw(potatoes lemons apricots apples bananas ostriches flamingoes);
my @short_strs = grep { length $_ < 8 } @strs;
for my $str (@short_strs) {
print "$str\n";
}
This produces the output:
lemons
apples
bananas
Example 2
What if you have a list of files, and want only those ending in
.html? We can use grep together with a regular expression: #!/usr/bin/perl
use strict;
use warnings;
my @files = qw(index.html test.html test.txt Makefile home.html help.doc README.txt);
my @html_files = grep { /\.html$/ } @files;
for my $file (@html_files) {
print "$file\n";
}
This produces the output:
index.html
test.html
home.html
See also
perldoc -f grep
No comments:
Post a Comment