By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,542 Members | 1,434 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,542 IT Pros & Developers. It's quick & easy.

map function with hashes .

P: 51
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.
Jun 13 '08 #1
Share this Question
Share on Google+
1 Reply


KevinADC
Expert 2.5K+
P: 4,059
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. }
  6.  
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.

http://perldoc.perl.org/functions/map.html
Jun 13 '08 #2

Post your reply

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