Thursday, January 6, 2011

Using map and grep in Perl

Using map and grep in Perl

map and grep are very useful functions in Perl, they help to reduce longer lines of 
codes in a script.

map function evaluates a block of code on each element of a given list and returns 
the result of each such evaluation. 

grep function evaluates an expression on each element of a given list and returns 
those elements for which the expression evaluated to true. 

#!/usr/bin/perl

print "content-type: text/html \n\n";

@cities = ("Kolkata","Mumbai","Hydrebad","Kohima","Delhi");

%cities_hash = map {$_ => 1} @cities; # storing the list of cities from @cities array in a new hash, $_ here represents individual element in @cities array

foreach $city (keys%cities_hash) {
 print "$city\n";
}

@cities_with_k = grep {/^k/i} @cities; # filtering cities starting with k and storing them in a new array

print "Cities starting with K: @cities_with_k\n";

Output:
-------
Delhi
Kohima
Mumbai
Kolkata
Hydrebad
Cities starting with K: Kolkata Kohima