map function with hashes .

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pavanponnapalli
    New Member
    • May 2008
    • 51

    #1

    map function with hashes .

    hi ,
    I have come across a code as below in the perldoc:

    %hash = map { get_a_key_for($ _) => $_ } @array;

    Could anybody tell me the meaning of the above line? please explain map function with reference to hashes. I have understood the meaning of map in general and have worked with an example. But i could not understand the meaning of the same with respect to hashes. So please help me.

    Thanks & Regards,
    pavan.
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    map is nothing more than a loop, similar to a "for" or "foreach" loop, although there are differences. In your example it is just turning the array into a hash but applying some processing first before using the elements of the array as a hash key. Your code is the same as:

    Code:
    @array = (1..100);
    %hash = map {$_ => $_} @array;
    foreach my $key (keys %hash) {
       print "The key is $key and the value is $hash{$key}\n";
    }
    The difference is that your code has a subroutine in the map block to preprocess the hash keys in some manner.

    While the entire statement works in a right to left manner, within the map block, things work left to right. Here is a sort of flow chart using arrows and numbers to show the order and direction of processing:

    Code:
    output <--(3) map {(2)-->} <-- (1) input
    the input ( could be an array or list or hash or anything that returns a list, like the grep function ) is read into the map function one element at a time, inside the map block each element is processed starting with the left most set of statements inside the map block and working to the right. When the map block is finished processing the elements it sends them to the output, which is a list of some kind, a hash or arrray most likely.

    http://perldoc.perl.or g/functions/map.html

    Comment

    Working...