2011-05-05 45 views
1

在這個例子中,我想從$ref讀出字母「d」的散列訪問一個元素:在Perl,你怎麼從哈希

$ref={a,b,c,{d,e}} 
+1

是這個有效的Perl?也許你應該從教程開始[per​​ldoc](http://perldoc.perl.org/index-tutorials.html)。此外,你有什麼嘗試? – Benoit 2011-05-05 11:04:43

+7

這是有效的Perl,有點。它與'my $ ref = {a =>「b」,c => {d =>「e」}}'相同,並且不能在嚴格模式下工作。 – Quentin 2011-05-05 11:12:50

回答

2

print keys %{$ref->{c}};將針對特定的(可怕的)例如工作。它可能解決你的問題,也可能解決不了你的問題,因爲我們不知道問題實際是什麼。

4
# Start using these! 
use strict; 
use warnings; 

# A more standard way of writing your example. 
my $ref = { a => "b", c => { d => "e", f => "g" } }; 

# How to access elements within the structure. 
my $inner = $ref->{c}; 
print $_, "\n" for 
    $inner->{d}, # e 
    keys %$inner, # d f 
    $ref->{c}{d}, # e (directly, without using intermediate variable). 
; 

欲瞭解更多信息,請參閱Perl Data Structures Cookbook