in reply to Re: Variable scoping outside subs
in thread Variable scoping outside subs

You're missing my point, comment it out and see what happens.

Replies are listed 'Best First'.
Re: Re: Re: Variable scoping outside subs
by Anonymous Monk on Oct 27, 2003 at 23:21 UTC
    I think you are likely confused by the fact that $var seems to be legally declared before the subroutine, but the subroutine is called before $var is declared. And yet, in the subroutine, $var has not been initialized to 1.

    In this case, the entire script is parsed and the my declaration is noted at compile time. The initialization of $var happens at runtime, except in your case you've exited before that point.

Re: Re: Re: Variable scoping outside subs
by sgifford (Prior) on Oct 27, 2003 at 23:26 UTC

    I agree the behavior is strange. It seems that Perl is processing the declaration at compile-time, which is why the variable exists when the sub is declared, but isn't processing the assignment until that line is reached in runtime, which never happens.

    Perhaps you've touched on an area where the right thing to do is ambiguous, so Perl's idea of what to do differs from yours.

    Several people have already shown you ways to make this work, by making sure the my statement precedes the call to test in both compile- and run-time.

Re:3 Variable scoping outside subs
by QM (Parson) on Oct 27, 2003 at 23:38 UTC
    my has both compile-time and run-time effects. See Abigail's comment in Unusual Closure Behaviour, though that's not directly related to your problem. [and damn those spelling variations]

    When the my line is commented out, I suspect that Perl is not complaining about the missing declaration because of the compile-time effect, even though the line is never executed.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of