#! /Usr/bin/perl-wuse strict; my @ array = (5, 'A', 'C', 10, 'B '); my @ new_array = (MAP {$ _ * 2 if M/\ D/;} @ array); print "@ new_array \ n"; print $ # new_array; # print join (",", @ new_array), "\ n ";
Map usage Example 2
1. Convert the file name to the file size
@ Sizes = map {-S $ _} @ file_names;
-S is a file test operator that returns the size of a file. Therefore, the above statement returns the size of each file in the @ file_names array, and the result is also an array.
2. Convert the array to hash: Find the index of an array value
Instead of repeated search arrays, we can use map to convert the array to hash, and use the hash keyword for direct search. The following map usage is simpler and more efficient than repeated array searches.
@ Teams = QW (Miami Oregon Florida Tennessee Texas Oklahoma Nebraska LSU Colorado Maryland); % Rank = map {$ teams [$ _], $ _ + 1} 0 .. $ # teams; print "Colorado: $ rank {Colorado} \ n"; print "Texas: $ rank {Texas} (Hook 'em, horns !) \ N ";
The printed result is:
Colorado: 9
Texas: 5 (Hook 'em, horns !)
The above code is easy to understand. 0 .. $ # teams is a list. $ # teams represents the lower value of @ teams's last element (9 in this example). Therefore, this list contains the numbers 0-9. Map traverses the above list, sets each list element to $ _ temporarily, and calculates $ _ In The Middle Of {}; {$ teams [$ _], $ _ + 1}. Here, a list of two elements is returned after each calculation. The list result is an array value and the corresponding array subscript plus 1. Are you clear?
When calculating each list element, a list of two elements is generated, so the total map result can be considered as a hash. The hash keyword is an array element, and the hash value is the corresponding array subscript plus 1.
Http://www.chinaunix.net/jh/25/632333.html