perl中的双花括号

Chr*_*ris 11 perl curly-braces

我在线查看perl代码并遇到了一些我以前从未见过的东西,但却无法知道它在做什么(如果有的话).

if($var) {{
   ...
}}
Run Code Online (Sandbox Code Playgroud)

有谁知道双花括号是什么意思?

ike*_*ami 15

那里有两个陈述."if"语句和裸块.裸块是仅执行一次的循环.

say "a";
{
   say "b";
}
say "c";

# Outputs a b c
Run Code Online (Sandbox Code Playgroud)

但作为循环,它们确实会影响next,last并且redo.

my $i = 0;
say "a";
LOOP: {  # Purely descriptive (and thus optional) label.
   ++$i;
   say "b";
   redo if $i == 1;
   say "c";
   last if $i == 2;
   say "d";
}
say "e";

# Outputs a b b c e
Run Code Online (Sandbox Code Playgroud)

(nextlast没有下一个元素的情况相同.)

它们通常用于创建词法范围.

my $file;
{
   local $/;
   open(my $fh, '<', $qfn) or die;
   $file = <$fh>;
}
# At this point,
# - $fh is cleared,
# - $fh is no longer visible,
# - the file handle is closed, and
# - $/ is restored.
Run Code Online (Sandbox Code Playgroud)

目前还不清楚为什么要在这里使用一个.


或者,它也可以是散列构造函数.

sub f {
   ...
   if (@errors) {
      { status => 'error', errors => \@errors }
   } else {
      { status => 'ok' }
   }
}
Run Code Online (Sandbox Code Playgroud)

是的缩写

sub f {
   ...
   if (@errors) {
      return { status => 'error', errors => \@errors };
   } else {
      return { status => 'ok' };
   }
}
Run Code Online (Sandbox Code Playgroud)

Perl偷看了大括号,猜测它是裸循环还是哈希构造函数.既然你没有提供大括号的内容,我们分不清楚.

  • +1表示哈希构造函数的可能性. (2认同)

dax*_*xim 11

它通常是与使用的一招do,见语句修饰perlsyn.

可能是作者想要用next类似的东西跳出街区.