【发布时间】:2012-06-05 20:24:30
【问题描述】:
我在网上查看 perl 代码,发现了一些我以前从未见过的东西,但不知道它在做什么(如果有的话)。
if($var) {{
...
}}
有人知道双花括号是什么意思吗?
【问题讨论】:
-
我认为他们什么也没做。我认为它们相当于在 if 块中添加另一个代码块。
标签: perl curly-braces
我在网上查看 perl 代码,发现了一些我以前从未见过的东西,但不知道它在做什么(如果有的话)。
if($var) {{
...
}}
有人知道双花括号是什么意思吗?
【问题讨论】:
标签: perl curly-braces
那里有两个陈述。一个“if”语句和一个bare block。裸块是只执行一次的循环。
say "a";
{
say "b";
}
say "c";
# Outputs a b c
但作为循环,它们确实会影响 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
(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' }
}
}
简称
sub f {
...
if (@errors) {
return { status => 'error', errors => \@errors };
} else {
return { status => 'ok' };
}
}
Perl 窥探大括号以猜测它是裸循环还是散列构造函数。由于您没有提供大括号的内容,我们无法判断。
【讨论】:
这是do 通常使用的技巧,请参阅chapter Statement Modifiers in perlsyn。
大概作者想跳出next之类的块吧。
【讨论】:
在if 的情况下,它们可能相当于单括号(但这取决于块内部和if 外部的内容,参见
perl -E ' say for map { if (1) {{ 1,2,3,4 }} } 1 .. 2'
)。但是,有理由使用双括号,next 或do,请参阅perlsyn。例如,尝试运行几次:
perl -E 'if (1) {{ say $c++; redo if int rand 2 }}'
并尝试用单括号替换双括号。
【讨论】:
如果没有更多代码,很难说出它们的用途。可能是拼写错误,也可能是裸块,请参阅chapter 10.4 The Naked Block Control Structure in Learning Perl。
裸块为块内的变量添加词法范围。
【讨论】:
if 之后的第一组大括号不是已经提供了范围吗?为什么要筑巢?我对 perl 基本上一无所知,所以也许对人们来说很明显,但对我来说却不是!
if (1) {{ my $x = 1; } { my $x = 2; }}
$var 并以在 if 块之外不可见的方式在裸块中使用它。
{{ 可用于跳出“if 块”。我有一些代码包含:
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
【讨论】: