http://www.perlmonks.org?node_id=231359

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

Hi

I've got a sub which calls another sub to generate and populate a hash. This parent sub then needs to use the hash generated in the child sub. Problem is, the parent sub doesn't seem to want to read the hash generated in the child sub correctly.

Here's my code:
sub foo { ... my %locations = &bar($dbh); ... my $location_text = $locations{$ref->{'location'}}; } sub bar { my $dbh = shift; my $sql_loc = qq|SELECT * FROM ndmw_location|; my $sth = $dbh->prepare($sql_loc); $sth->execute or die("..."); my %locations; while (my $ref = $sth->fetchrow_hashref()) { my $id = $ref->{'id'}; my $location = $ref->{'location'}; $locations{$id} = $location; } $sth->finish; return %locations; }
$location_text returns sometimes nothing and othertimes a seemingly random value.

I've put Data::Dumper into the parent sub and have observed that the hash comes back into the parent sub correctly so I'm at a loss as to why I can't get at that data.

If I throw all the code into one sub and not try and split it into sub-subs, it all works as expected.

Anyone got any ideas what I might be doing wrong?

Thanks!

- wil