in reply to Array of Hashes in subroutines.
Not that it'll make a difference here, but you should always enable warnings in your code - either via '-w' in the shebang, or 'use warnings' right below it. It'll save you lots of grief.
As to your code - whenever you see that 'ARRAY(0xDEADBEEF)' output that you didn't expect, it's a sure sign that you forgot to dereference the variable you're trying to print. If that variable is something simple, like '$x', and you know that it's supposed to be an array, just stick an '@' sigil in front of it - @$x - and Perl will do the right thing. When it's more complex than that - say, $x is a pointer to an anonymous list and you want the first element - then use the IDO ("little arrow") syntax, '$x->[0]'. Last of all, when it's some ungodly mess that you don't even feel like figuring out - e.g., '($bar->(qw/fiddle glop/))[1][9]', and you want to get at the underlying array, just wrap the whole thing in curly braces and treat it like an array name. I.e.,
print @{($bar->(qw/fiddle glop/))[1][9]}; # Print the whole list print ${($bar->(qw/fiddle glop/))[1][9]}[3]; # Print the 4th element print ${$x}[0]; # You can even use it i +nstead of the IDO - but it's kinda ugly :)
'HASH(0xC0FFEE)' or whatever is pretty similar; obviously, you'd use '%' for the sigil and '{}' for the subscripts. For more about dereferencing, see perldoc perlref.
As to the script itself, try this:
#!/usr/bin/perl -w use strict; sub display { my $ref = shift; for my $k (sort keys %$ref){ print "$k: @{$ref->{$k}}\n"; } } my %hash1; $hash1{fruit} = [ qw/apple orange plum/ ]; $hash1{vegetable} = [ qw/leek carrot peas/ ]; display (\%hash1); for my $k (sort keys %hash1){ print "$k: @{$hash1{$k}}\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Array of Hashes in subroutines.
by AnomalousMonk (Archbishop) on Sep 19, 2010 at 00:24 UTC |