views:

271

answers:

1

Say I had something like:

# %superhash is some predefined hash with more than 0 keys;
%hash = ();
foreach my $key (keys %superhash){
    $superhash{ $key } = %hash;
    %hash = ();
}

Would all the keys of superhash point to the same empty hash accessed by %hash or would they be different empty hashes?

If not, how can I make sure they point to empty hashes?

+4  A: 

you need to use the \ operator to take a reference to a plural data type (array or hash) before you can store it into a single slot of either. but in the example code given, if referenced, each would be the same hash

the way to initialize your data structure is:

foreach my $key (keys %superhash) {
     $superhash{ $key } = {}; # new empty hash reference
}

but initialization like this is largely unnecessary in Perl due to autovivification (creating appropriate container objects when a variable is used as a container).

my %hash;

$hash{a}{b} = 1;

now %hash has one key, 'a', which has a value of an anonymous hashref, containing the key/value pair b => 1. arrays autovivify in the same manner.

Eric Strom
Agreed. No need to carry an extra hash around when Perl doesn't need it.
Zaid
How would I access the keys of $hash{a}? When I try `foreach my $rk (keys $hash{a}){...` it gives me an error: the type must be hash
piggles
Ah I got it: `$deref = $hash{a}` and then `foreach $key (keys %$deref){...`
piggles
@Mechko - no need for that, just: `foreach my $key (keys %{$hash{$a}}) { ...`
plusplus
@Mechko - see http://perlmonks.org/?node=References+quick+reference
ysth
@plusplus Ah. It's curlies. I kept trying with parentheses. It didn't work very well :(
piggles
@Mechko => you should read through perlref, perllol and perldsc on perldoc.perl.org, which contain a good overview of how perl's references work, and how to use them to create complex data structures
Eric Strom
Thanks. I only started perl at 2am yesterday. So far it's all been instinct.
piggles