用do{}创建内联子程序

do {} 这种语法能把几条语句组合成单条表达式,这点有些类似于内联子程序.

my $file = do {
  local $/;
  open my ($fh) , '<' , $filename or die;
  <$fh>;
};

最后的表达式回座位代码块的返回值返回。

借助do语句,利用最后求值的表达式既返回值这一特性,合并目标变量,代码的意义就会变得直接明确:

my ($thousand_sep,$decimal_sep) = do {
  if ($local eq 'European' )  { qw{.,}   }
  elsif ($local eq 'English' )  {qw(,)}
};

有时候我们会借助do来弱化错误处理相关的代码。 比如打开一组文件,但不希望在某次打开失败时立即中止。

foreach my $file (@files) {
  open my ($fh) , '<',$file  or do {warn ..; next};
  .... do sutff ...;
}
posted @ 2013-03-13 20:27  新闻官  阅读(148)  评论(0编辑  收藏  举报