perl - 我对 Perl 自动生成示例的分析

标签 perl

考虑这段 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/

相关文章:

bash - 如何在 sed 和 awk(和 perl)中搜索和替换任意文字字符串

regex - 无法在 Perl 中转义美元符号

使用包分隔符时的 perl 字符串插值

Perl 难以将值传递给函数

perl - abs_path 与主目录

perl - SOAP::Lite 中可能存在错误吗?

perl - *nix : perform set union/intersection/difference of lists

linux - 检查程序是否存在

python - Perl 到 Python 和 cx_Oracle、fetchrow_array

perl - 如何在 Perl 中对 HTTP GET 查询字符串进行编码?