08678 发表于 2015-12-27 15:22:54

perl编程中的map函数示例

转自:http://www.jbxue.com/article/14854.html
发布:脚本学堂/Perl编辑:JB01   2013-12-20 10:20:01【大 中 小】
本文介绍下,perl编程中的map函数的用法,分享一些per 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,获得所有的书名中包含的单词,且转化为大写。


复制代码代码示例:
  #!/usr/bin/perl -w
#
  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 -w
# site: www.jbxue.com
#
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
  以上介绍了perl中map函数的几个例子,希望对大家有所帮助。
页: [1]
查看完整版本: perl编程中的map函数示例