Perl, Tutorials

Minimal things to know about map function in Perl

Sending
User Rating 5 (1 vote)

  Perl is such a nice language that even a beginner can write the fully working code by using simpler things available in Perl.  More you know about Perl  more crazy you will be about it. Its very famous for one liner stuffs and even it has many functions which can minimize our code, run time and our work too!

Map function in Perl is a nice example for it. You can replace you whole foreach code with map in a single line.

  • Perl’s  map functions evaluates expression or a set of block for each element of an array and returns another new array.
  • Each array element is get stored in $_ (local lexical), then it evaluates according to expression or block and pass it to new list of arrays.
  • As hash is nothing but an associative array so you can apply map on that also ex:  %hashVal = map  { lc($_)=>$_  }  @array;   (block example ) or %hashval  = map  + ( lc($_)=>$_ ) ,@array;    (expression example)
  • I just found few different way to write same map function: All will do the same thing , Its just use of regular expression and to differentiate block and expression things.
  • # Method 1 @ucnames = map( ( join ” “,  map (ucfirst lc , split)  ) ,@names);
    print “\n########## Printing Values of \@ucnames using map Method 1 ############\n”;
    print Dumper(@ucnames);
  • #Method 2 @ucnames = map { join ” “,  map {ucfirst lc} split  } @names;
    print “\n########## Printing Values of \@ucnames using map Method 2 ############\n”;
    print Dumper(@ucnames);
  • #Method 3 @ucnames = map { join ” “, map { s/^(.)(.*)$/uc($1) . lc($2)/e; $_ } split } @names;
    print “\n########## Printing Values of \@ucnames using map Method 3 ############\n”;
    print Dumper(@ucnames);
  • Another example :
    Suppose we have an array whose elements are double quoted and we need to remove that. map function could be very useful in this case
     my @out = map { s/”//g; $_ } @arr;

Note: Block does not need comma but expression needs coma explicitly see the examples using { block } and (expression). In simple ,it is

  • map { block } @array or
  • map {expression}, @array or
  • map + { block } , @array (will be treated as expression so comm. Is needed after } )or
  • map (expression , @array)

For fully working code on map function please visit this link For more details on map click here

Share your Thoughts