围绕变量的花括号 [英] Curly braces surrounding variable

查看:61
本文介绍了围绕变量的花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,我想弄清楚,我什至不知道它的语法是否正确(我猜是练习的一部分!)

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.

谢谢各位!

推荐答案

使用参考" perlref 文档的部分解释.

2. 在您将标识符(或标识符链)作为变量或子例程名称的一部分放置的任何地方,您都可以用返回正确类型引用的 BLOCK 替换标识符.换句话说,前面的例子可以这样写:

2. Anywhere you’d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this:

   $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. 在您将标识符(或标识符链)作为变量或子例程名称的一部分放置的任何地方,您都可以将标识符替换为包含正确引用的简单标量变量类型:

1. Anywhere you’d put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type:

   $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}.

这篇关于围绕变量的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆