Search code examples
perlrecursionhashmap

Perl Recursive Explanation


I have following script that need to understand

&main('key_1');

sub main {
    @{$tmp{'key_1'}} = ("A", "B");
    @{$tmp{'A'}} = ("C");

    &test_recurse(\%tmp, 'key_1');
}

sub test_recurse {
    my ($hash, $cell) = @_;
    foreach my $cur_subcell (@{$hash->{$cell}}){
        &test_recurse($hash, $cur_subcell);
    }
    print "X($cell)\n";
}  

The output:

X(C)
X(A)
X(B)
X(key_1)

I want to understand why the key_1 is printing at the last? I am expecting the key_1 might not be printed at all.


Solution

  • In a comment, you say:

    I am just thinking that as if the variable $cell has been replace by C, A, B why the key_1 is coming back at the end.

    And I think that's probably a good indication of where the confusion lies.

    Your test_recurse() subroutine starts with this line:

    my ($hash, $cell) = @_;
    

    That defines two new variables called $hash and $cell and then populates them from @_. Because these variables are declared using my, they are lexical variables. That means they are only visible within the block of code where they are declared.

    Later on in test_recurse() you call the same subroutine again. And, once again, that subroutine starts with the same declaration statement and creates another two variables called $hash and $cell. These two new variables are completely separate from the original two variables. The original variables still exist and still contain their original values - but you can't currently access them because they are declared in a different call to the subroutine.

    So when your various calls to the subroutine end, you rewind back to the original call - and that still has the original two variables which still hold their original values.