perl的map函数的使用:
语法
map EXPR,LIST
map BLOCK LIST
定义和使用
对list中的每个元素执行EXPR或BLOCK,返回新的list。对每一此迭代,$_中保存了当前迭代的元素的值。
返回值
如果返回值存储在scalar标量中,则代表map()返回数组的元素个数;
如果返回值存储在list中,则代表map()函数的数组;
实例1 (将单词首字母大写)
#
!/usr/bin/perl -w
@myNames
=
(
'jacob'
,
'alexander'
'ethan'
'andrew'
);
@ucNames
map
(
ucfirst
$numofucNames
);
foreach
$key
(
){
print
"$key\n"
;
}
;
结果为
Jacob
Alexander
Ethan
Andrew
4
实例2 (获得所有的书名中包含的单词,且转化为大写)
my
@books
(
'Prideand Prejudice'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'emma'
'Masfield Park'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'Senseand Sensibility'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'Nothanger Abbey'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'Persuasion'
'Lady Susan'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'Sanditon'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'The Watsons'
@words
{
split
/\
s
+/,
$_
)}
;
@uppercases
uc
$upword
"$upword\n"
;
}
结果为 (Perl map函数的输入数组和输出数组不一定等长,在split起过作用之后,当然@words的长度要比@books长了。)
PRIDEAND
PREJUDICE
emmA
MASFIELD
PARK
SENSEAND
SENSIBILITY
NOTHANGER
ABBEY
PERSUASION
LADY
SUSAN
SANDITON
THE
WATSONS
实例3 (将多余2位的数字提取到新的list)
my
@buildnums
(
'R010'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'T230'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'W11'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'F56'
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; color:rgb(0,
'dd1'
);
@nums
/
\
d{
2
})
}
$num
(
){
"$num \n"
}
$a = 'RRR3ttt';
@yy = $a=~/RRR.*ttt/;
$numofyy = $a=~/RRR.*ttt/;
print "@yy\n";
print "$numofyy\n" ;
@yy2 = $a=~/(RRR).*(ttt)/;
$numofyy2 = $a=~/(RRR).*(ttt)/;
print "@yy2\n";
print "$numofyy2\n";
print "$1 $2";
结果为 (正则表达式匹配后返回的为数组或长度,取决于表达式中是否有()或者接收的变量类型)
010
230
11
56
1
1
RRR ttt
1
RRR ttt
完!