1

我有一个像这样的 perl 变量。我如何访问内部属性(如“706”)?

my @config = [
        {
        'x' => [ 565, 706 ],
        'y' => [ 122 ],
        'z' => 34,
        'za' => 59,
    }
];

编辑: print Dumper($config[0]);产量:$VAR1 = undef;

看起来我使用$config[0][0]->{x}[1];. 为什么我必须使用 [0][0] (一个很清楚,但他秒...)?

EDIT2: 我很抱歉改变了数据结构,但是给我的定义改变了。

4

2 回答 2

4

您的变量相当于:

my $config = [
    'x', [ 565, 706 ],
    'y', [ 122 ],
    'z', 34,
    'za', 59,
];

所以如果你想得到706,你可以这样做:

print $config->[1][1];

根据问题中的新数据更新

有了更新的问题,您现在可以通过以下方式访问:

say $config->[0]{x}[1];

根据新数据结构进行新更新

根据您提供的最后更新的数据结构:

my @config = [
        {
        'x' => [ 565, 706 ],
        'y' => [ 122 ],
        'z' => 34,
        'za' => 59,
    }
];

您将一个包含自身哈希 {...} 的匿名数组 [...] 分配给数组 @config,这将使用匿名数组填充 @config 的第一个元素

say Dumper \@config;

$VAR1 = [
          [
            {
              'y' => [
                       122
                     ],
              'za' => 59,
              'x' => [
                       565,
                       706
                     ],
              'z' => 34
            }
          ]
        ];
say $config[0][0]{x}[1];  #prints 706

我想你想做的任何一个:

my $config = [
        {
        'x' => [ 565, 706 ],
        'y' => [ 122 ],
        'z' => 34,
        'za' => 59,
    }
];
say $config->[0]{x}[1]; #prints 706



my @config = (
        {
        'x' => [ 565, 706 ],
        'y' => [ 122 ],
        'z' => 34,
        'za' => 59,
    }
);
say $config[0]{x}[1];  #prints 706
于 2011-01-31T13:06:46.133 回答
3

[编辑: 遵循转移问题的定义。]

鉴于:

my @config = ( 
  [
    { # NB: insertion order ≠ traversal order
        "x"  => [ 565, 706 ],
        "y"  => [ 122 ],
        "z"  => 34,
        "za" => 59,
    },
  ],
);

然后这将做到这一点:

# choice §1
print $config[0][0]{"x"}[-1];   # get 1ˢᵗ row’s xᵗʰ row’s last element

当然理解这只是语法糖:

# choice §2
print $config[0]->[0]->{"x"}->[-1];   # get 1ˢᵗ row’s xᵗʰ row’s last element

这只是语法糖:

# choice §3
print ${ $config[0] }[0]->{"x"}->[-1];   # get 1ˢᵗ row’s xᵗʰ row’s last element

这反过来只是语法糖:

# choice §4
print ${ ${ $config[0] }[0] }{"x"}->[-1];   # get 1ˢᵗ row’s xᵗʰ row’s last element

这又是语法糖:

# choice §5
print ${ ${ ${ $config[0] }[0] }{"x"}}[-1];   # get 1ˢᵗ row’s xᵗʰ row’s last element

当然,这相当于:

# choice §6
print ${ ${ ${ $config[0] }[0] }{"x"} }[ $#{ ${ ${ $config[0] }[0] }{"x"} } ];   # get 1ˢᵗ row’s xᵗʰ row’s last element
于 2011-01-31T12:41:56.043 回答