Henri has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I would like to modify (grow) a hash of hashes iteratively within a loop through a subroutine and in the end print what's stored in the hash. To do this I am passing a reference to the hash to the subroutine - at least I thought so. However, I get the error "Global symbol "%misfits" requires explicit package name at ...". This is the code that I can't get to work:

#Main my @whole_world = (); my $misfits = {}; # the reference foreach my $individual (@whole_world) { ($ok_ones, $misfits) = find_misfits(\@whole_world, $misfits); } print_misfits($misfits); # sub sub find_misfits { my ($whole_world, $misfits) = @_; my %candidates = (); # do stuff to find the misfits, ie compare the genetic setup of in +dividuals # add individuals that don't fit to $misfits $misfits{$stand}{$mother}{$offspring} = {%{$candidate{$stand}{ +$mother}{$offspring}}}; return ($misfits, some more structures); }
Any help would be greatly appreciated.

Replies are listed 'Best First'.
Re: Growing a Hash of Hashes via its reference
by almut (Canon) on Feb 17, 2009 at 19:41 UTC
    $misfits{$stand}{$mother}{$offspring}

    You probably want:

    $misfits->{$stand}{$mother}{$offspring}

    Without the arrow, Perl thinks you want to access a hash %misfits, not a hash reference (how should it disambiguate?), and thus use strict is complaining...

Re: Growing a Hash of Hashes via its reference
by Bloodnok (Vicar) on Feb 17, 2009 at 19:41 UTC
    In sub find_misfits, $misfits is a hash ref., so you need to change...
    $misfits{$stand}{$mother}{$offspring} = {%{$candidate{$stand}{$mother} +{$offspring}}};
    to read
    $misfits->{$stand}{$mother}{$offspring} = {%{$candidate{$stand}{$mothe +r}{$offspring}}};
    A user level that continues to overstate my experience :-))
Re: Growing a Hash of Hashes via its reference
by toolic (Bishop) on Feb 17, 2009 at 19:35 UTC
    Maybe you need to localize $misfits in sub find_misfits?
    my ($whole_world, $misfits) = @_;

    It is difficult to say because the code you posted has syntax errors and is not a complete example that we can run. So, we can not duplicate your error.

    The strictures will probably help you:

    use warnings; use strict; use diagnostics;
Re: Growing a Hash of Hashes via its reference
by Henri (Novice) on Feb 17, 2009 at 20:02 UTC
    Thanks for the solution. Henri