简体   繁体   中英

Extracting information from a perl data structure

Forgive a novice question as I am learning Perl. I have some code like such:

my $familyInfo = [{
            'dad' => 'donald',
            'mom' => 'helen',
            'sister' => 'cate',
}];

Note that this code I cannot modify in any way. What I want to do is extract the mom from this data structure:

my $mother = $familyInfo{mom};
print "mother: $mother\n";

my $mother = $familyInfo[0]{mom};
print "mother: $mother\n";

This doesn't work at all. It doesn't assign anything to $mother. What I'm not understanding is exactly what type of structure the initialization creates, and exactly how to use it. Any information you can provide that can help me make sense of this twisted language's syntax would be helpful!

There are two layers to dereference, the outer layer being an array ref, and the inner layer being a hash ref.

my $mother = $familyInfo->[0]{mom};

Or to put it another way, $familyInfo holds a reference to an anonymous array. There is only one element. That element contains a reference to an anonymous hash.

The important component that is different from the sample code you posted is the dereferencing operator , -> .

Without the arrow operator, you're telling Perl that $familyInfo[0] is an element of @familyInfo (which it is not, @familyInfo doesn't even exist). What does exist, is $familyInfo ; a scalar containing an array reference, which has to be dereferenced if you want to get at its elements. perldoc perlreftut should help to clarify the syntax.

If the above doesn't work for you, then your input data doesn't match what you've shown. In that case, use Data::Dumper to get a closer look at your input data.

use Data::Dumper;
print Dumper $familyInfo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM