问题描述
我有一段代码,我想弄清楚,我什至不知道它的语法是否正确(我猜是练习的一部分!)
I have this piece of code that I'm trying to get my head around, I don't even know if its syntactically correct (part of the exercise I guess!)
%{$records}
大括号是什么意思?我见过同样的情况,但使用 @
运算符而不是 $
如果这有所不同.
What do the curly braces signify? I've seen the same case but with a @
operator used instead of the $
if that makes a difference.
谢谢各位!
推荐答案
2. 在您将标识符(或标识符链)作为变量或子例程名称的一部分放置的任何地方,您都可以用返回正确类型引用的 BLOCK 替换标识符.换句话说,前面的例子可以这样写:
$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = "January";
${$hashref}{"KEY"} = "VALUE";
&{$coderef}(1,2,3);
$globref->print("output\n"); # iff IO::Handle is loaded
在您的情况下,$records
必须是对哈希的引用(因为最外面的 %
),{$records}
是返回引用的块,%{$records}
给出原始哈希值.
In your case, $records
must be a reference to a hash (because of the outermost %
), {$records}
is a block that returns the reference, and %{$records}
gives the original hash.
花括号包围一个真正的块.事实上,你可以用
The curly braces surround a bona fide block. In fact, you could replace the code above with
%{ if ($records) { $records } else { $default_records } }
但正如文档前面所指出的,即使是您问题中的较短版本也可以简化.
But even the shorter version from your question could be simplified, as pointed out earlier in the documentation.
1. 在您将标识符(或标识符链)作为变量或子例程名称的一部分放置的任何地方,您都可以将标识符替换为包含正确引用的简单标量变量类型:
$bar = $$scalarref;
push(@$arrayref, $filename);
$$arrayref[0] = "January";
$$hashref{"KEY"} = "VALUE";
&$coderef(1,2,3);
print $globref "output\n";
因为 $records
是一个简单的标量,%$records
是底层哈希.
Because $records
is a simple scalar, %$records
is the underlying hash.
如果 $records
是对数组的引用,则取消引用它的语法将是 @$records
或 @{$records}
.
If instead $records
were a reference to an array, the syntax for dereferencing it would be @$records
or @{$records}
.
这篇关于围绕变量的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!