in reply to static variable hack

When my is encountered at run-time, a directive is placed on the stack to clear the variable. Since you're not executing my, the directive is not placed on the stack, so the variable doesn't get cleared.

The docs warn against using this side-effect of internal mechanics. (Emphasis in original.)

Note: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ...) is undefined.

If you wish to have a static variable, use the following. (Surrounding curlies are optional.)

{ my $static; sub func { ... } }

See recent thread Lexical scope variable is not undef'ed.

Replies are listed 'Best First'.
Re^2: static variable hack (BEGIN)
by tye (Sage) on Oct 29, 2007 at 22:44 UTC
    { my $static; sub func { ... } }

    I'd updated that to:

    BEGIN { my $static= ...; sub func { ... } }

    The BEGIN allows this to work just fine under mod_perl, and protects against people calling the subroutine before the $static is initialized. The subroutine is defined when it is compiled, so it is best to initialize the $static before that.

    - tye        

Re^2: static variable hack
by InfiniteLoop (Hermit) on Oct 29, 2007 at 20:15 UTC
    Right, thanks. Also I have ran this code with "use strict;". If, "my" isn't executed, why doesn't the "strict" complain ?
      Creating the variable is my's compile-time effect. The my gets compiled whether it gets executed or not.
        Apologies, thanks.