2012-10-05 48 views
1

我正在使用Amazon Perl模塊,它返回對哈希引用數組的引用,作爲$ record_sets,包含記錄集數據,而我很難解開它。我可以使用數據自卸車打印數據,但我需要能夠操縱數據。下面是提供用於將模塊Perl幫助解引用對包含記錄集數據的哈希引用數組的引用

由於事先的文檔:

#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.' 
] 
+0

請注意,'type =>'MX''後面缺少一個逗號。 – choroba

回答

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"; 
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"; 
}