Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Is this BEGIN construct supposed to work?

by Anonymous Monk
on Nov 02, 2011 at 22:09 UTC ( #935504=perlquestion: print w/ replies, xml ) Need Help??
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
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        

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 ... }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://935504]
Approved by sundialsvc4
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2014-08-22 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (151 votes), past polls