第十七章 高级Perl技巧
1. 用eval捕获错误
类似于 try-catch
eval {
# process
};
if ($@) {
print "An error occuured ($@), Continuing\n";
}
my $res = eval {$a / $b}; #除数为0时不会崩溃,返回undef
2. 用grep筛选列表
每个元素执行一次代码块,返回的还是列表;
my @odd_num = grep { $_ % 2} 1..1000; #取奇数存入数组
my @matching_lines = grep {/\bfred\b/i} <FILE> ; #从文件过滤匹配行
my @matching_line = grep /\bfred\b/i,<FILE>; #grep的简单形式
3. 用map对列表进行转换
和grep一样,也是每个元素执行一次代码块,返回的还是列表;
my @data = map { sprintf("%25s\n", $_) } @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, undef, $count) = split /:/; #只获取第1个和第4个元素
my (undef, undef, 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, 0, 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; #使用哈希切片代表哈希里的元素