Using map and grep
Kevin Eye
Buffalo Perl Mongers
grep
- grep BLOCK LIST
- Evaluates the BLOCK 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.
- filter out comments
@foo = grep {!/^#/} @bar
- how many comments in @bar
$num_comments = grep {!/^#/} @bar
- does @bar have any comments
$has_comments = grep {!/^#/} @bar
- first comment in @bar
($first_comment) = grep {!/^#/} @bar
map
- map BLOCK LIST
- Evaluates the BLOCK for each element of
LIST (locally setting "$_" to each element) and
returns the list value composed of the results of
each such evaluation.
- Evaluates BLOCK in
list context, so each element of LIST may produce
zero, one, or more elements in the returned value.
- translate numbers to characters
@chars = map { chr } @nums
- double every value in @nums
@nums = map { $_ * 2 } @nums
- make a hash
%hash = map { getkey($_) => $_ } @values
- is 'something' in @unindexed_array?
%index = map { $_ => 1 } @unindexed_array;
exists $index{'something'}
Putting it together
open FH, 'names.txt';
@names = <FH>;
foreach $name (@names) {
next unless $name =~ /\w/; # filter blank lines
@firstlast = split / /, $name;
$lastfirst = join ', ', reverse @firstlast;
push @rnames, $lastfirst;
}
@sorted = sort @rnames;
foreach $name (@sorted) {
print $name;
}
Putting it together
open FH, 'names.txt';
@names = grep { /\w/ } <FH>;
foreach $name (@names) {
@firstlast = split / /, $name;
$lastfirst = join ', ', reverse @firstlast;
push @rnames, $lastfirst;
}
@sorted = sort @rnames;
foreach $name (@sorted) {
print $name;
}
Putting it together
open FH, 'names.txt';
@names = grep { /\w/ } <FH>;
foreach $name (@names) {
push @rnames, join ', ', reverse split / /, $name;
}
@sorted = sort @rnames;
foreach $name (@sorted) {
print $name;
}
Putting it together
open FH, 'names.txt';
@names = grep { /\w/ } <FH>;
@rnames = map { join ', ', reverse split / / } @names;
@sorted = sort @rnames;
foreach $name (@sorted) {
print $name;
}
Putting it together
open FH, 'names.txt';
@names = grep { /\w/ } <FH>;
@rnames = map { join ', ', reverse split / / } @names;
@sorted = sort @rnames;
print for @sorted;
Putting it together
open FH, 'names.txt';
@names = grep { /\w/ } <FH>;
@rnames = map { join ', ', reverse split / / } @names;
@sorted = sort @rnames;
print for @sorted;
Putting it together
open FH, 'names.txt';
print for sort
map { join ', ', reverse split / / }
grep { /\w/ }
<FH>;
Putting it together
open FH, 'names.txt';
print for # see sequence of filters from bottom up
# sort lines (alpha by last name)
sort
# firstname lastname -> lastname, firstname
map { join ', ', reverse split / / }
# filter out blank lines
grep { /\w/ }
# read all lines
<FH>;
Putting it together
open FH, 'names.txt';
print for sort map { join ', ', reverse split / / } grep { /\w/ } <FH>;