1. Perl
  2. builtin functions
  3. here

map function - transformation of all elements of an array

Use the map function to convert all the elements of a array . Each element of @array is passed to the default variable $_, so perform the necessary conversions in the code block {}. The last evaluated conversion statement is added to @mapped in order.

# Conversion of all elements of the array
@mapped = map {conversion} @array;

Example

This is an example that doubles all elements using map. If @nums is (1, 2, 3) then @doubled is (2, 4, 6).

# Double all elements
my @nums = (1, 2, 3);
my @doubled = map {$_ * 2} @nums;

This is an example that deletes the first string of all elements using map. If @strs is ('& nbsp; & nbsp; a', '& nbsp; & nbsp; b', '& nbsp; & nbsp; & nbsp; c'), then @trimed is ('a', 'b', 'c') Become.

# Excluding leading blanks
my @strs = ('a', 'b', 'c');
my @trimed = map {$_ =~ s/^\s+//; $_} @strs;

You can also convert one element into two elements. If @keys is ('a', 'b', 'c') then @mapped is (a => 1, b => 1, c => 1).

# Convert to two elements
my @keys = ('a', 'b', 'c');
my @mapped = map {$_ => 1} @keys;

What can be written on the map can also be written on foreach statement. Maps are often used in Perl because they are simpler to write.

# for
my @nums = (1, 2, 3);
my @doubled;
for my $num (@nums) {
  push @doubled, $num * 2;
}

Reference "Array of Perl"

See below for a description of Perl's "arrays".

Related Informatrion