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