in reply to Variable scoping outside subs

Line 6 is never evaluated. Execution ends at line 4.

If you want line 6 to execute before test is called, place it before the call to &test().

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

Replies are listed 'Best First'.
Re: Re: Variable scoping outside subs
by Anonymous Monk on Oct 27, 2003 at 22:59 UTC
    You're missing my point, comment it out and see what happens.
      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

      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.

      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.