对 x 个数据结构取消引用 x 次

De-reference x number of times for x number of data structures

我在我设法解决的一个 perl 脚本中遇到了一个障碍,但我真的不明白为什么它会这样工作。我一直在网上搜索,但没有找到合适的解释。

我有一个 returns 对数组散列的引用的子例程。哈希键是简单的字符串,值是对数组的引用。

我打印出与每个键关联的数组元素,像这样

for my $job_name (keys %$build_numbers) {
    print "$job_name => ";
    my @array = @{@$build_numbers{$job_name}};  # line 3
    for my $item ( @array ) {
        print "$item \n";
    } 
}

虽然我能够打印出键和值,但我并不真正理解第 3 行背后的语法。

我们的数据结构如下:

对散列的引用,其值是对填充数组的引用。

要提取数组的元素,我们必须: - 取消引用哈希引用,以便我们可以访问密钥 - 取消引用与键关联的数组引用以提取元素。

最后一个问题是:

希望有人能帮忙澄清一下。

第 3 行对您的哈希引用进行了 slice,但这是一种非常奇怪的方式来执行您想要执行的操作,因为 a) 您通常不会对单个元素进行切片,并且 b)有更清晰、更明显的语法,可以使您的代码更易于阅读。

如果您的数据看起来像这样:

my $data = {
    foo => [0 .. 9],
    bar => ['A' .. 'F'],
};

那么你的例子的正确版本应该是:

for my $key (keys(%$data)) {
    print "$key => ";

    for my $val (@{$data->{$key}}) {
        print "$val ";
    }

    print "\n";
}

产生:

bar => A B C D E F
foo => 0 1 2 3 4 5 6 7 8 9

如果我理解你的第二个问题,答案是如果你使用正确的语法,你可以访问复杂数据结构的精确位置。例如:

print "$data->{bar}->[4]\n";

将打印 E.

补充推荐阅读:perlref, perlreftut, and perldsc

使用数据结构可能会很困难,具体取决于它的制作方式。

我不确定您的 "job" 数据结构是否正是这样,但是:

#!/usr/bin/env perl

use strict;
use warnings;
use diagnostics;


my $hash_ref = {

 job_one => [ 'one', 'two'],
 job_two => [ '1','2'],

};

foreach my $job ( keys %{$hash_ref} ){

 print " Job => $job\n";

 my @array = @{$hash_ref->{$job}};

 foreach my $item ( @array )
 {

        print "Job: $job Item $item\n";
 }

}

您有一个哈希引用,您可以迭代作为数组的键。但是这个数组的每一项都可以是另一个引用或一个简单的标量。

基本上,您可以像在第一个循环中那样使用 ref 或撤消 ref。

有一份文档,您可以查看更多详细信息here

所以回答你的问题:

Final question being: - When dealing with perl hashes of hashes of arrays etc; to extract the elements at the "bottom" of the respective data structure "tree" we have to dereference each level in turn to reach the original data structures, until we obtain our desired level of elements?

这取决于你的数据结构是如何制作的,如果你已经知道你在寻找什么,那么获取值会很简单,例如:

%city_codes = (

a => 1, b => 2,

);

my $value = $city_codes{a};

复杂的数据结构伴随着复杂的代码。