What does this do? Well, 'my' creates a new lexical variable, in this case '%keymap'. What happens next is that this new variable is initialised with the hash you get from dereferencing $_[0] (hopefully a hash reference). i.e. You are copying the data to a new hash.my %keymap = %{$_[0]};
So far so good, except that this new hash is thrown away (as all lexical variables are) at the end of the scope. In this case, your 'my' declaration has scope of the load_keymap function.
The easiest way to get around this is to try not to dislike using references directly. i.e. If your load_keymap function began with:
and continued with:my $file_name = shift; my $hr = shift;
Then all would be well.... $hr->{$2} = $1;
Below is the code snippet I used to try and be sure what was going on. You can change between the types of behaviour by altering the $ALWAYS_USE_REF constant at the top.
Hope this helps.
#!/usr/local/bin/perl use strict; my $ALWAYS_USE_REF = 1; main( @ARGV ); exit 0; sub main { my %hash; recursively_foo_my_hash( \%hash, 5 ); print_hash_ref_contents( \%hash ); return 1; } sub recursively_foo_my_hash { my $hr = shift; print "RFMH called with hash ref: $hr\n"; my %new_hash = %{ $hr }; my $depth = shift; $hr = \%new_hash unless $ALWAYS_USE_REF; return 1 unless $depth > 0; $hr->{"foo_$depth"} = rand(); # Add some data recursively_foo_my_hash( $hr, $depth - 1 ); return 1; } sub print_hash_ref_contents { my $hr = shift; print "Hash ref [$hr] contains:\n"; foreach my $k ( sort keys %$hr ) { print "$k -> $hr->{$k}\n"; } return 1; }
In reply to Re: Recursion + hash
by jbert
in thread Recursion + hash
by karmas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |