Map in Perl

Source: Internet
Author: User
#! /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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.