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

sub routine { my %hash; BEGIN { $hash{KEY} = "string"; } }
Note how the BEGIN treats %hash as if it were a file-scoped global. The keys that are set in %hash are still set when routine() starts and are retained between calls to routine().

Comment on Is this BEGIN construct supposed to work?
Download Code
Replies are listed 'Best First'.
Re: Is this BEGIN construct supposed to work?
by JavaFan (Canon) on Nov 02, 2011 at 22:21 UTC
    What makes you think the BEGIN treats %hash as if it were a file-scoped global? Try moving the my %hash; *after* the begin block.

    Note also that your claim the keys are retained doesn't seem to be true:

    use strict; use warnings; use 5.010; sub routine { my %hash; BEGIN { $hash{KEY} = "string"; } $hash{FOO} = "something else"; say join " ", keys %hash; } routine; routine; routine; __END__ Variable "%hash" will not stay shared at /tmp/hh line 12. KEY FOO FOO FOO
Re: Is this BEGIN construct supposed to work?
by ikegami (Pope) on Nov 02, 2011 at 23:47 UTC
    Maybe you want state?
    sub routine { state %hash = ...; ... %hash ... }

    It's kinda like the following, but the assignment is actually done the first time state is evaluated.

    my %hash; BEGIN { %hash = ...; } sub routine { ... %hash ... }
Re: Is this BEGIN construct supposed to work? (does not)
by tye (Cardinal) on Nov 02, 2011 at 22:21 UTC

    I don't see $hash{KEY} being retained except on the very first call to routine(). This is what I expected as the %hash gets (re)initialized when the containing scope is left.

    - tye