2011-05-05 40 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