Perl Map
map EXPR,LIST
Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns
the list value composed of the results of each such evaluation. In scalar context, returns the total
number of elements so generated. Evaluates BLOCK or EXPR in list context, so each element of LIST may
produce zero, one, or more elements in the returned value.
Example 1: Finding square of the numbers
my @arr = (1..5);
say "@arr \n";
Prints: 1 2 3 4 5
my @unique = map { $_ * $_ } @arr;
say "@unique \n";
Prints: 1 4 9 16 25
Example 2: Square even, cube odd numbers. Use Perl modulus operator to distinguish odd and even numbers.
my @arr = (1..5);
say "@arr";
Prints: 1 2 3 4 5
my @unique = map { $_%2 ? $_*$_*$_ : $_*$_ } @arr;
say "@unique";
Prints: 1 4 27 16 125
Example 3: Square even, cube odd numbers. Use Perl and operator to distinguish odd and even numbers.
my @arr = (1..5);
say "@arr";
Prints: 1 2 3 4 5
my @unique = map { $_&1 ? $_*$_*$_ : $_*$_ } @arr;
say "@unique";
Prints: 1 4 27 16 125
Example 4: Convert to uppercase
my @lover = qw("aa bbb ccc ddddd eeee fff");
say "@lover";
Prints: "aa bbb ccc ddddd eeee fff"
my @upper = map { uc } @lover;
say "@upper";
Prints: "AA BBB CCC DDDDD EEEE FFF"
www.oocgi.com.
|