perl的map函數的使用:
語法
map EXPR, LIST
map BLOCK LIST
定義和使用
對list中的每個元素執行EXPR或BLOCK,返回新的list。對每一此迭代,$_中保存了當前迭代的元素的值。
返回值
如果返回值存儲在scalar標量中,則代表map()返回數組的元素個數;
如果返回值存儲在list中,則代表map()函數的數組;
實例1 (將單詞首字母大寫)
@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@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)
my @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