467,114 Members | 1,306 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,114 developers. It's quick & easy.

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,
Jun 13 '08 #1
  • viewed: 3469
1 Reply
Expert 2GB
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:

Expand|Select|Wrap|Line Numbers
  1. @array = (1..100);
  2. %hash = map {$_ => $_} @array;
  3. foreach my $key (keys %hash) {
  4.    print "The key is $key and the value is $hash{$key}\n";
  5. }
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:

Expand|Select|Wrap|Line Numbers
  1. 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.

Jun 13 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Damien Morton | last post: by
8 posts views Thread by Ben Holness | last post: by
2 posts views Thread by MartyNg | last post: by
6 posts views Thread by vamsinadella | last post: by
23 posts views Thread by nsa.usa@gmail.com | last post: by
11 posts views Thread by January Weiner | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.