Main Content

Filtering and altering Perl lists with grep and map

Archive - Originally posted on "The Horse's Mouth" - 2007-08-23 11:14:03 - Graham Ellis

In Perl, you can process whole lists (arrays) in single operations - and that's very efficient at run time as it avoids the needs for loops, and the needed for Perl's Virtual Machine to go back to the byte code (in effect source) for each member.

The map function applies an opertion to each member of a list, and returns a list of the same length, with each element duely mapped. The input to the transform function is $_ - so with embedded calls to functions like uc there's no need to specify it. But if you're going to take 1 off each member then you'll find $_ turn up in the code.

The grep function applies an operation to each member of a list, and returns the member unaltered for inclusion in the output list if the result is a true value. Otherwise, the input member is not included in the output list. So the output list from grep is going to be shorter than the incoming list, but the members themselves won't be modified.

@numbers = (10,30,40,33,45,32,43,22);
 
# Subtract 1 of each member of @numbers
@numbers = map($_-1,@numbers);
# Return a list of all numbers that are possible days of the month
@digit = grep( $_ <=31 ,@numbers);
 
print ("@digit\n");
 
@people = ("tim","steve","JASPER","DaVeY");
 
# Force all input members to lower case, then capitalise the first letter
@people = map(ucfirst lc,@people);
print "@people\n";