in reply to Re^3: File-scoped lexicals and eval scope?
in thread File-scoped lexicals and eval scope?

I guess I don't consider $value if 0; a trick. The idea is that, if sub initialize wants to have its use of $value be bound to the outer lexical even after that lexical's scope is exited, it needs to explicitly mention it. scalar($value); works as well, as does 0 if $value;.  Any of them should be accompanied by a comment. If you want to be pedantic, the latter is best documented as not triggering a 'Useless use' warning.

Replies are listed 'Best First'.
Re^5: File-scoped lexicals and eval scope?
by jbert (Priest) on Nov 11, 2007 at 22:12 UTC
    I called it a trick because it exploits undefined behaviour in the language. perl 5.10, 5.12 or some future version may or may not preserve the same behaviour, so it seems to me bad practice to promulgate it's use.

    As I'm sure you know, perldoc perlsyn states:

    NOTE: The behaviour of a "my" statement modified with a statement modi‐ fier conditional or loop construct (e.g. "my $x if ...") is undefined. The value of the "my" variable may be "undef", any previously assigned value, or possibly anything else. Don’t rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

      Ah. I wasn't suggesting my $value if 0;, nor would that work to make the sub close over the outer $value. I was suggesting $value if 0;, to incorporate a reference to the outer $value into the sub, while avoiding the "Useless use of a variable in void context" warning you'd get from a bare $value;.
        Ah....sorry. Stupid of me.

        That does raise an interesting question as to what code a perl optimiser would be allowed to remove. You'd really like the optimiser to be able to nuke code like this:

        while (tight_loop) { write_to_log("Some msg involving $somevar") if REALLY_HEAVY_DEBUG; some_more_code(); }
        if the constant evaluated to 0. I guess if $somevar was relevant to the debugging then it would be closed over anyway, but that is a bit too subtle.