in reply to static variable hack
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 |