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 ( [id://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().

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 (Patriarch) 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 (Sage) 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        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2024-03-28 12:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found