Perl - map to process every member of a list (array)
Archive - Originally posted on "The Horse's Mouth" - 2008-10-09 23:38:09 - Graham EllisPerl's map function (like array_walk in PHP) allows you to do something to every member of a list - thus it often saves you the need to write a loop into your Perl, saves the Perl runtime going back time and again to the interbal byte code generated by the compiler, and can be very efficient.
There aren't a large number of map examples in the training course notes that I use; in Perl there are many ways of doing anything and there are always alternatives but - as appropriate - I do add extra demonstrations in as I present the material. Here - four days into a five day course - are my examples of map so far this week:
@vals = map($_*5,@vals);
Take all the members of a list called @vals, multiply each of them by 5, are return them to a list of the same name (@vals), overwriting the original
$plist = join(", ",map (ucfirst lc, @peeps));
Take each element of the list in @peeps (probably people's names) and convert them all to lower case, then capitalise the first letter of their first name. Join the resulting names together with a space between each of them, and put the resulting single scalar string that results into a variable called $plist
map(printf("%20s %d\n",$_,$counter{$_}),@hio[0..9]);
Take the first ten elements of a list called @hio which in this example contained a sorted list of host computer names) and print out, formatted, the corresponding members of the hash called %counter - which contained elements keyed to those host names, with values which were the number of times that the particular host had accessed our server.
This last example is notable in that it makes no use of (throws away) the list returned by map - which will just be a list of "1" values indicating success - the important result is the effect of the 10 operations of printf