考虑这段 Perl 代码,
$array[$x]->{“foo”}->[0]= “January”;
我分析这段代码如下:“数组”中索引为 $x 的条目是一个 hashref。对于这个哈希,当它的键是“foo”时,它的值是一个数组,这个数组的第0个元素是“January”。我的分析是否正确?谢谢。
最佳答案
您对结构的分析是正确的,但是相关的自动生成示例更像是:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.10.0; # say
my @array;
# check all levels are undef in structure
say defined $array[0] ? 'yes' : 'no'; # no
say defined $array[0]{foo} ? 'yes' : 'no'; # no
say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no
# then check again
say defined $array[0] ? 'yes' : 'no'; # yes (!)
say defined $array[0]{foo} ? 'yes' : 'no'; # yes (!)
say defined $array[0]{foo}[0] ? 'yes' : 'no'; # no
请注意,您没有分配任何内容,实际上您所做的只是检查是否存在某些内容。当您检查某个级别 x
的多级数据结构时,会发生自动生成,然后突然所有较低级别 (x-1 ... 0
) 突然存在。
这意味着
say defined $array[0]{foo}[0] ? 'yes' : 'no';
实际上等同于
$array[0] = {};
$array[0]{foo} = [];
say defined $array[0]{foo}[0] ? 'yes' : 'no';
关于perl - 我对 Perl 自动生成示例的分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8599456/