You have an array of "pointers" to anon hashes. Data::Dumper is a SUPER cool thing to help visualize what is going on.
Below, I have a foreach loop that processes every hash_ref in @rec.
$hash_ref->{'name'} yields the name in that record
@{$hash_ref->{'kids'}} is a bit trickier. If this was just one kid, then it would work like a name. But there are multiple kids and this is an array of kids.
Below I show how to print @demo. $hash_ref->{'kids'} fetches one thing just like accessing $hash_ref->{'name'} did. But now we have to de-reference that single thing which is a "pointer" to array. In Perl when you have a "subscripted thing" and you want to de-reference it, you need to enclose it in brackets,{}. I did that, then I said that this is an array de-reference '@' and bingo, this is now just like printing @demo. In other words, you need to tell "@" what to operate upon. @$hash_ref->{'kids'} would mean something completely different. I want "@" to operate not just upon the value $hash_ref, but upon the whole thing that {$hash_ref->{'kids'}} "points to".
An array in a scalar context is the number of things in that array. I think others have covered that point.
#!/usr/bin/perl -w use strict; use Data::Dumper; my @demo =('xyz', 'qrs'); my @rec = ( { name => 'Nancy', address => 613, kids => ['abc', 'def'], }, { name => "Betty", address => 845, kids => ['xyz', 'qrs'], }, ); print Dumper \@rec; print "DEMO: @demo\n"; foreach my $hash_ref (@rec) { print "$hash_ref->{'name'} struggles with: ", "@{$hash_ref->{'kids'}}\n"; } __END__ $VAR1 = [ { 'name' => 'Nancy', 'kids' => [ 'abc', 'def' ], 'address' => 613 }, { 'name' => 'Betty', 'kids' => [ 'xyz', 'qrs' ], 'address' => 845 } ]; DEMO: xyz qrs Nancy struggles with: abc def Betty struggles with: xyz qrs
In reply to Re^3: print array of hashes
by Marshall
in thread print array of hashes
by fionbarr
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |