“{}”如何(大括号)创建一个散列,为什么我可以将其存储为标量?

发布于 2024-12-17 11:19:47 字数 275 浏览 1 评论 0原文

perltoot 中是这样的代码:

$rec = {
  name  => "Jason",
  age   => 23,
  peers => [ "Norbert", "Rhys", "Phineas"],
};

这是一个字符串还是某种哈希值(我认为哈希值已声明)与%)?

In perltoot is this code:

$rec = {
  name  => "Jason",
  age   => 23,
  peers => [ "Norbert", "Rhys", "Phineas"],
};

Is this a string or some sort of hash (I thought hashes were declared with %)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还不是爱你 2024-12-24 11:19:48

它是对哈希的引用(某种指针)。引用(如 Perl 中以“$”开头的任何内容)是一个标量,在本例中是“指向”非标量值的标量。

  @ta = (10,20,30); # array
  $tb = [10,20,30]; # reference to an array
  %tc = (name => 'John', age => 23); # hash
  $td = {name => 'John', age => 23}; # reference to a hash

  print( $ta[1] . "\n");
  print( $tb->[1] . "\n");

  print( $tc{'name'} . "\n");
  print( $td->{'name'} . "\n");

理解引用对于任何普通的 Perl 编程来说都是至关重要的。例如,您需要使用引用来创建嵌套结构(数组的数组等)。

It's a reference (sort of a pointer) to a hash. And a reference (as anything that begins with '$' in Perl) is an scalar, in this case a scalar that "points" to a non-scalar value.

  @ta = (10,20,30); # array
  $tb = [10,20,30]; # reference to an array
  %tc = (name => 'John', age => 23); # hash
  $td = {name => 'John', age => 23}; # reference to a hash

  print( $ta[1] . "\n");
  print( $tb->[1] . "\n");

  print( $tc{'name'} . "\n");
  print( $td->{'name'} . "\n");

Understanding references is essential to any more than casual Perl programming. For example, you need to use references to make nested structures ( arrays of arrays, etc).

始终不够爱げ你 2024-12-24 11:19:48

{ } 创建一个哈希值和对其的引用,并返回后者。

{ a => 1, b => 2 }

大致相当于

do { my %anon = ( a => 1, b => 2 ); \%anon }

此运算符记录在 perlref 中。

{ } creates both a hash and a reference to it, and it returns the latter.

{ a => 1, b => 2 }

is roughly equivalent to

do { my %anon = ( a => 1, b => 2 ); \%anon }

This operator is documented in perlref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文