---
title: "别人总结的perl技巧"
author: "standalone"
date: "2011-05-21T15:08:33Z"
tags: []
categories: ["非技术"]
slug: "perl"
draft: false
lastmod: "2011-05-21T15:08:33Z"
id: 1053286
url: "https://standalone.iteye.com/blog/1053286"
---

1\. 用eval获得程序的执行错误  
$a = 10;  
$b = 0;  
$c = $a/$b;  
会发生什么？  
程序会crash,因为有浮点数异常。用eval就可以做到两全，既执行语言，又能在出现异常的时候不crash  
$a = 10;  
$b = 0;  
eval {$c = $a/$b};  
eval { ... }可以捕获执行的多条语句的错误结果。  
然后用$@可以得到错误原因。  
#!/usr/bin/perl  
$a = 10;  
$b = 0;  
eval {$c = $a/$b};  
if ($@) {  
    print "There was a error ($@)\\n";  
}else {  
    print "The result = $c\\n";  
}

2\. 用grep从列表里选取数据  
比如， 从1到100中取出所有的奇数  
#!/usr/bin/perl  
my @odds = grep { $_ % 2 } 1..100;  
print "$_ " foreach @odds;

3.用map传递列表的值  
比如你已经有了一个列表，如何把列表的每个值作为key建立一个hash?  
#!/usr/bin/perl  
use Data::Dumper;  
my @array = (a, b, c);  
my %hash = map { $_ =&gt; 1 } @array;  
print "hash:  ".Dumper(\\%hash);

grep和map有点类似，都是把list的值一一拿出来放进$\_，然后执行BLOCK {}中的语言，区别在于：  
grep： 返回在BLOCK{}中最后一句执行结果为真的$_  
map： 返回在BLOCK{}中最后的一句

4\. 选取list中的部分元素  
my @array = (a, b, c);  
my @new = @array\[ 0, 2];  
@new中将包含a和c

5\. 选取hash中的部分元素  
my @three\_scores = ($score{"barney"}, $score{"fred"}, $score{"dino"});  
my @three\_scores = @score{ qw/ barney fred dino/ };

用法@score{ ... }