perl:散列的自动生成作为对象-> new()的参数?

perl: autoivivifcation of hash as parameter of object->new()?

来自 perlootut:

  my $cage = File::MP3->new(
      path          => 'mp3s/My-Body-Is-a-Cage.mp3',
      content       => $mp3_data,
      last_mod_time => 1304974868,
      title         => 'My Body Is a Cage',
  );

我不明白这是怎么回事。它看起来是自动激活的,如果是这样,那么 new 正在传递 class 名称和对新哈希的引用?

不涉及自动复活。您可能会对 => operator:

的使用感到困惑

The => operator is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores.

虽然在声明哈希时经常使用 =>,但它本身并不创建哈希。

您发布的代码等同于

my $cage = File::MP3->new(
    'path',          'mp3s/My-Body-Is-a-Cage.mp3',
    'content',       $mp3_data,
    'last_mod_time', 1304974868,
    'title',         'My Body Is a Cage',
);

这只是将包含八个项目的列表传递给 new 方法。

=> 也称为 宽逗号 ,它的作用就像逗号一样——除了以下情况:

  1. 左边的是裸词
  2. bareword 有资格作为变量名(即没有奇怪的字符)

在那种情况下,粗逗号将引用左侧的裸词。

使用粗逗号是因为:

  1. 有些人发现输入粗逗号比在左侧的裸词周围输入引号更容易

  2. 粗逗号表示lhs和rhs之间的关系。然而,这种关系只是视觉上的——由函数来确定这种关系应该是什么。

Although => is often used when declaring hashes, it doesn't create a hash by itself.

也就是说:

use strict;
use warnings;
use 5.016;
use Data::Dumper;

my %href = (
    'a', 10,
    'b', 20,
    'c', 30,
);

say $href{'a'};

say Dumper(\%href);


--output:--
10
$VAR1 = {
          'c' => 30,
          'a' => 10,
          'b' => 20
        };

perl 不是 ruby。