in reply to static variable hack

This line
my $static = 42 if 0;

is optimized away after compilation, because the 0 is a constant:

qwurx [shmem] ~ > perl -MO=Deparse sub foo { my $static = 42 if 0; print "static is now $static\n"; $static++; } foo() for 1..5; __END__ sub foo { '???'; print "static is now $static\n"; $static++; } ; foo foreach (1 .. 5); __DATA__ - syntax OK

Note the '???' showing a statement swallowed by the optimizer.

Because optimization happens after compile, the lexical variable declared via my already has been seen and allocated for the subroutine's scope.

That's why that construct passes strictures. And - that' the hack - because the my declaration isn't seen ever again at runtime, the lexical inside that sub doesn't get cleared on subsequent invocations of the sub.

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: static variable hack
by ikegami (Patriarch) on Oct 29, 2007 at 20:26 UTC

    Overall right. Just nitpicking two details.

    First, optimization is not a factor. It's simply whether the my gets executed or not.

    Second, you're also off on the timing. Clearing occurs at end of scope. It's triggered by the my, but it doesn't occurs when the my is encountered. (By the way, that's also when a new my variable is created if the refcount is greater than 1.)

    Both points can be observed in

    sub foo { my ($reset) = @_; my $x if $reset; # Will reset at end of scope if $reset is true. return ++$x; } print foo(0), "\n"; # 1 print foo(0), "\n"; # 2 print foo(1), "\n"; # 3 print foo(0), "\n"; # 1 print foo(0), "\n"; # 2