加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl语言入门(第五版) 读书笔记(十一)---高级Perl技巧

发布时间:2020-12-16 00:04:01 所属栏目:大数据 来源:网络整理
导读:第十七章 高级Perl技巧 1. 用eval捕获错误 ?类似于 try-catch ?eval { ?# process ?}; ?if ($@) { ? print "An error occuured ($@),Continuingn"; ?} ?my $res = eval {$a / $b}; #除数为0时不会崩溃,返回undef ? 2. 用grep筛选列表 每个元素执行一次代码

第十七章 高级Perl技巧
1. 用eval捕获错误
?类似于 try-catch
?eval {
?# process
?};
?if ($@) {
? print "An error occuured ($@),Continuingn";
?}
?my $res = eval {$a / $b}; #除数为0时不会崩溃,返回undef
?
2. 用grep筛选列表
每个元素执行一次代码块,返回的还是列表;
my @odd_num = grep { $_ % 2} 1..1000;? #取奇数存入数组
my @matching_lines = grep {/bfredb/i} <FILE> ; #从文件过滤匹配行
my @matching_line = grep /bfredb/i,<FILE>; #grep的简单形式

3. 用map对列表进行转换
和grep一样,也是每个元素执行一次代码块,返回的还是列表;
my @data = map { sprintf("%25sn",$_) } @data;
my @format_data = map { &big_money($_) } @data;
print "Powers of 2 :n",map "t".(2 ** $_)."n",0..15 ;

4. 切片
切片是从列表中获取少量值的最简单方法
my @items =? split /:/ ;
my (undef,$card_num,undef,$count) = split /:/; #只获取第1个和第4个元素
my (undef,$aaa) = stat $filename;
my $aaa = (stat $filename)[3] ;
my $card_num = (split /:/)[1];
my ($card_num,$count) = (split /:/)[1,4]; #返回下标为1和4的两个元素

5. 数组切片
my ($first,$last) = (sort @names)[0,-1]; # -1表示最后一个元素
my @numbers = @names[9,2,1,0]; #数组切片可以省略括号,获取@names中的5个值
@names[ 2,5 ] 与 ($names[2],$names[5]) 含义相同

6. 哈希切片 my @three_scores = ($score{"barney"},$score{"fred"},$score{"dino"}); #普通方法从%score获取元素 my @three_scores = @score{ qw/barney fred dino/} ; #切片方法从%score中获取元素 my @players = qw/barney fred dino/; my @bowling_scores = (195,205,30); @score{ @players } = @bowling_scores; #使用哈希切片代表哈希里的元素

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读