Perl帮助解引用包含记录集数据的哈希引用数组的引用

时间:2012-10-05 21:27:55

标签: perl amazon-route53

我正在使用一个Amazon Perl模块,该模块将对哈希引用数组的引用作为$ record_sets返回,包含记录集数据,并且我很难解除引用它。我可以使用数据转储器打印数据,但我需要能够操作数据。以下是为模块提供的文档

提前致谢:

#list_resource_record_sets
#Lists resource record sets for a hosted zone.
#Called in scalar context:

$record_sets = $r53->list_resource_record_sets(zone_id => '123ZONEID');

#Returns: A reference to an array of hash references, containing record set data. Example:

$record_sets = [
{
name => 'example.com.',
type => 'MX'
ttl => 86400,
records => [
'10 mail.example.com'
]
},
{
name => 'example.com.',
type => 'NS',
ttl => 172800,
records => [
'ns-001.awsdns-01.net.',
'ns-002.awsdns-02.net.',
'ns-003.awsdns-03.net.',
'ns-004.awsdns-04.net.'
]

2 个答案:

答案 0 :(得分:4)

当你有一个数组引用时,例如$ x = ['a','b','c'],您可以通过两种方式取消引用。

print $x->[0]; # prints a
print $x->[1]; # prints b
print $x->[2]; # prints c

@y = @{$x}; # convert the array-ref to an array (copies the underlying array)
print $y[0]; # prints a
print $y[1]; # prints b
print $y[2]; # prints c

hash-ref的工作方式相同,只是它使用花括号。例如。 $ x = {a => 1,b => 2,c => 3}。

print $x->{a}; # prints 1
print $x->{b}; # prints 2
print $x->{c}; # prints 3

%y = %{$x}; # convert the hash-ref to a hash (copies the underlying hash)
print $y{a}; # prints 1
print $y{b}; # prints 2
print $y{c}; # prints 3

将此应用于您的示例,该示例具有嵌套结构,您可以执行此操作。

for my $x ( @{$record_sets} ) {
  print $x->{name}, "\n";
  print $x->{type}, "\n";

  for my $y ( @{$x->{records}} ) {
    print $y, "\n";
  }
}

# or something more direct
print $record_sets->[0]->{name}, "\n";
print $record_sets->[0]->{records}->[1], "\n";

答案 1 :(得分:0)

$ record_sets是一个数组引用。要取消引用它,您可以使用

my @array = @{ $record_sets };

每个记录集都是一个哈希引用。

for my $record_set ( @{ $record_sets } ) {
    my $set = %{ $record_set };
}

例如,要获取名称和记录(数组引用):

for my $record_set ( @{ $record_sets } ) {
    print $record_set->{name},
          ': ',
          join ', ', @{ $record_set->{records} };
    print "\n";
}