The simple answer is that it is due to the line:
my %keymap = %{$_[0]};
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.

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:

my $file_name = shift; my $hr = shift;
and continued with:
... $hr->{$2} = $1;
Then all would be well.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.