Reputation: 1471
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' },
};
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?
Thank you in advance
Upvotes: 3
Views: 476
Reputation: 185254
Try doing this :
print $data1->[1]->{name}; # ARRAY ref
print $data3->{2}->{name}; # HASH ref
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.
Like Chris Charley said, take a look to the tutorial on data structures
To help you understanding what your scalar ref looks like, use Data::Dumper , ex :
print Dumper $data1;
print Dumper $data3;
Should output :
$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
}
};
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.
Upvotes: 6