in reply to Why no stay shared warning?

To get the "won't stay shared" warning, you have to have something like:

sub a { my $x; sub b { $x } }
Your my $foo isn't inside a subroutine so you just have one lexical variable scoped to that bare block. If the my was inside your up subroutine, then each call to up would create a new instance of $foo and that would mean that your get subroutine wouldn't know which instances of $foo that you wanted it to use.

Since the bare block is only ever executed once, your my only ever creates one instance of the variable so it "stays shared". When a my is compiled, it declares the variable (which leaves it set to undef). When the my is executed, it initializes the variables. Executing the my a second or subsequent time creates a new instance of the variable and then initializes that. Even if you require or use a module more than once, the code for the module is only compiled and executed once (but the code for subroutines in that module could be executed more times or zero times).

The code you used would be a fine way to store module-specific results. If your block were in a different module, then it would be the module and not the caller storing them.

Updated.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re: Why no stay shared warning?
by tenya (Beadle) on May 05, 2001 at 19:40 UTC
    It seems that my $foo only creates a place for sub up to store values between calls. Why does initializing it to 20 not have an effect?
    Thanks
    use strict; use diagnostics; up(); up(); print "getfoo=",get(); { my $foo = 20; sub up { print "subup=$foo\n"; $foo++; sub get {$foo} } } prints: subup= subup=1 getfoo=2
      The reason is because $foo = 20 doesn't occur until after you've called all those functions.

      DECLARATION occurs at compile-time. ASSIGNMENT happens at run-time. Different things. my $foo = 20 has a compile-time effect (my) and a run-time effect ($foo = 20).

      For your desired action, you'd need something like:
      my $foo; BEGIN { $foo = 20 }


      japhy -- Perl and Regex Hacker