Perl 嵌套结构 [英] Perl nested structures
问题描述
我有一个关于 Perl 中复杂结构的问题
I have a question regarding complicated structures in Perl
my $data1 = [
+{ id => 1, name => 'A' },
+{ id => 2, name => 'B' },
+{ id => 3, name => 'C' },
];
my $data3 = +{
1 => +{ id => 1, name => 'A' },
2 => +{ id => 2, name => 'B' },
3 => +{ id => 3, name => 'C' },
};
我应该如何打印B"?那是什么样的数据结构?以及关于 Perl 嵌套结构(散列引用、数组引用等)的任何易于理解的好参考?
How should I print "B"? What kind of data structure is that? And any nice reference on Perl nested structures (hash references, array references, etc.) that is eay to understand?
提前致谢
推荐答案
尝试这样做:
print $data1->[1]->{name}; # ARRAY ref
print $data3->{2}->{name}; # HASH ref
这是从 perl ARRAY 和 HASH 引用中取消引用.
This is de-reference from a perl ARRAY and HASH ref.
->
取消引用.只需要第一层地板",例如:
The ->
de-reference explicitly. It's only needed for the first "floor", ex :
print $data1->[1]{name};
print $data3->{2}{name};
也能用.第二个和更多是可选的.
Works too. The 2nd and more are optionals.
就像 Chris Charley 所说的,查看 数据结构教程
Like Chris Charley said, take a look to the tutorial on data structures
为了帮助您了解标量 ref 的外观,请使用 Data::Dumper,例如:
To help you understanding what your scalar ref looks like, use Data::Dumper , ex :
print Dumper $data1;
print Dumper $data3;
应该输出:
$VAR1 = [
{
'name' => 'A',
'id' => 1
},
{
'name' => 'B',
'id' => 2
},
{
'name' => 'C',
'id' => 3
}
];
$VAR1 = {
'1' => {
'name' => 'A',
'id' => 1
},
'3' => {
'name' => 'C',
'id' => 3
},
'2' => {
'name' => 'B',
'id' => 2
}
};
<小时>
对于 +{ }
语法,rra 给出了很好的回应:
For the +{ }
syntax, rra gives a good response :
在可以将大括号视为代码块而不是匿名哈希引用的地方消除歧义,但很少需要这样做.我猜代码包含它们是出于一种错误的愿望,即希望在可能不明确的地方保持清晰和一致.
disambiguates in places where the braces could be taken to be a code block instead of an anonymous hash reference, but one rarely needs that. I'm guessing the code contains them out of a misplaced desire to be clear and consistent with places where it could be ambiguous.
这篇关于Perl 嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!