perl中的双花括号

时间:2012-05-31 14:50:25

标签: perl curly-braces

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

if($var) {{
   ...
}}

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

5 个答案:

答案 0 :(得分:15)

那里有两个陈述。 “if”语句和bare block。裸块是只执行一次的循环。

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

# Outputs a b c

但是作为循环,它们会影响{​​{1}},nextlast

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 next的作用相同,因为没有下一个元素。)

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

last

目前还不清楚为什么要在这里使用它。


或者,它也可以是哈希构造函数。

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.

的缩写
sub f {
   ...
   if (@errors) {
      { status => 'error', errors => \@errors }
   } else {
      { status => 'ok' }
   }
}

Perl偷看大括号,猜测它是裸循环还是哈希构造函数。由于你没有提供大括号的内容,我们无法分辨。

答案 1 :(得分:11)

这是do通常使用的技巧,请参阅chapter Statement Modifiers in perlsyn

可能作者想要用next之类的东西跳出街区。

答案 2 :(得分:4)

如果是if,它们可能等同于单个括号(但它取决于块内和if之外的内容,参见

perl -E ' say for map { if (1) {{ 1,2,3,4 }} } 1 .. 2'

)。但是,使用双括号的原因有nextdo,请参阅perlsyn。例如,尝试多次运行:

perl -E 'if (1) {{ say $c++; redo if int rand 2 }}'

尝试用单个替换双括号。

答案 3 :(得分:0)

如果没有更多的代码,很难说它们被用于什么。它可能是一个错字,或者它可能是一个裸体块,请参阅chapter 10.4 The Naked Block Control Structure in Learning Perl

裸块会为块内的变量添加词法范围。

答案 4 :(得分:0)

{{可用于突破“if block”。我有一些代码包含:

if ($entry =~ m{\nuid: ([^\s]+)}) {{ # double brace so "last" will break out of "if"
    my $uid = $1;
    last if exists $special_case{$uid};
    # ....

}}
# last breaks to here
相关问题