perl中的map和grep
生活随笔
收集整理的這篇文章主要介紹了
perl中的map和grep
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
map
語(yǔ)法:
map EXPR, LIST
map BLOCK, LIST
語(yǔ)義:
對(duì)于LIST中的每個(gè)元素執(zhí)行EXPR或者BLOCK,如果返回值存儲(chǔ)在list中,則表示處理后的list,若返回值存儲(chǔ)在scalar中,則表示處理后的list中元素個(gè)數(shù)。下面是幾個(gè)例子.
單詞首字母大寫
sub test {my @names = (
'jacob',
'alexander',
'ethan',
'andrew',
);
my @new_names = map(ucfirst, @names);
foreach my $name (@new_names) {
print $name, "\n";
}
}
打印數(shù)組元素
print 相當(dāng)于 print $_
my @row_ary = (1, 3, 'abc', undef, 12, 'ddd', undef, undef) ;map { print } @row_ary;
替換數(shù)組元素
對(duì)于數(shù)組中每個(gè)元素,如果其值是undef,那么將其替換位x。
my @row_ary = (1, 3, 'abc', undef, 12, 'ddd', undef, undef) ;map { $_='x' unless $_ } @row_ary;
grep
grep的語(yǔ)法格式與map完全一樣,不過(guò)grep是通過(guò)判斷列表中每個(gè)元素是否滿足表達(dá)式或者塊來(lái)返回true和false,再根據(jù)true和false來(lái)決定最終的返回列表。所以grep多時(shí)用來(lái)過(guò)濾元素用的。
一個(gè)例子,找出一組單詞中的純數(shù)字單詞,如下。
sub test {my @words = (
'hello',
'123',
'B51',
'123abc',
'8',
);
my @numbers = grep { /^\d+$/ } @words;?
取數(shù)組中下標(biāo)為奇數(shù)的元素
my @nums = (2, 1, 3, 5, 4, 6);my @odd = @nums[grep { $_ & 1 } 0..$#nums];
@odd中值分別是1,5,6
分析,$#nums表示數(shù)組nums最后一個(gè)元素的下標(biāo),grep { $_ & 1} 取奇數(shù)下標(biāo),@nums[]取下標(biāo)為奇數(shù)的元素。
==
總結(jié)
以上是生活随笔為你收集整理的perl中的map和grep的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: MySQL(一)
- 下一篇: fortinate防火墙使用本地用户三步