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, @myNames);
$numofucNames = map(ucfirst, @myNames);
foreach $key ( @ucNames ){
print "$key ";
}
print $numofucNames;
@myNames = ('jacob', 'alexander', 'ethan', 'andrew');
@ucNames = map(ucfirst, @myNames);
$numofucNames = map(ucfirst, @myNames);
foreach $key ( @ucNames ){
print "$key ";
}
print $numofucNames;
结果为
Jacob
Alexander
Ethan
Andrew
4
实例2 (获得所有的书名中包含的单词,且转化为大写)
my@books = ('Prideand Prejudice','Emma', 'Masfield Park','Senseand Sensibility','Nothanger Abbey',
'Persuasion', 'Lady Susan','Sanditon','The Watsons');
my@words = map{split(/s+/,$_)}@books;
my@uppercases = map uc,@words;
foreach $upword ( @uppercases ){
print "$upword ";
}
my@words = map{split(/s+/,$_)}@books;
my@uppercases = map uc,@words;
foreach $upword ( @uppercases ){
print "$upword ";
}
结果为 (Perl map函数的输入数组和输出数组不一定等长,在split起过作用之后,当然@words的长度要比@books长了。)
PRIDEAND
PREJUDICE
EMMA
MASFIELD
PARK
SENSEAND
SENSIBILITY
NOTHANGER
ABBEY
PERSUASION
LADY
SUSAN
SANDITON
THE
WATSONS
实例3 (将多余2位的数字提取到新的list)
#!/usr/bin/perl -w
my @buildnums = ('R010','T230','W11','F56','dd1');
my @nums = map{/(d{2,})/} @buildnums;
foreach $num (@nums){
print "$num "
}
my @buildnums = ('R010','T230','W11','F56','dd1');
my @nums = map{/(d{2,})/} @buildnums;
foreach $num (@nums){
print "$num "
}
$a = 'RRR3ttt';
@yy = $a=~/RRR.*ttt/;
$numofyy = $a=~/RRR.*ttt/;
print "@yy
";
print "$numofyy
" ;
@yy2 = $a=~/(RRR).*(ttt)/;
$numofyy2 = $a=~/(RRR).*(ttt)/;
print "@yy2
";
print "$numofyy2
";
print "$1 $2";
结果为 (正则表达式匹配后返回的为数组或长度,取决于表达式中是否有()或者接收的变量类型)
010
230
11
56
1
1
RRR ttt
1
RRR ttt
完!