perl map
perl的map函數
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\n";
}
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\n";
}
結果為 (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?-wmy?@buildnums?=?('R010','T230','W11','F56','dd1');
my?@nums?=?map{/(\d{2,})/}?@buildnums;
foreach?$num?(@nums){
??print?"$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
?
完!
感謝,Thanks!
總結
- 上一篇: splite
- 下一篇: 安装Fedora 15后需做的25件事情