in reply to Conditional initialization of lexical (my) variables

I am not sure why you would expect any other behavior?

If the "unless" condition results in the "my my_var" not executing, then 'my_var' is never declared in the scope of the subroutine.

So when the next line assigns to 'my_var' - the assignment is done to a global variable.

So it is not persisting across calls, its just not scoped to the subroutine, but your entire file.

I always thought it was perfectly logical code, and I had used it in some situations as a convenient form of name overloading. Alas it looks like this caught out so many people they made it an error, and now people even claim it was a bug all along... which is nonsense.

  • Comment on Re: Conditional initialization of lexical (my) variables

Replies are listed 'Best First'.
Re^2: Conditional initialization of lexical (my) variables
by ikegami (Patriarch) on May 11, 2023 at 08:35 UTC

    So when the next line assigns to 'my_var' - the assignment is done to a global variable.

    That's not what's happening. It is indeed assigning to the lexical var.

    Running my pushes a directive on the stack that clears the lexical var on scope exit. This is what's being skipped in the OP's code.

Re^2: Conditional initialization of lexical (my) variables
by LanX (Saint) on May 11, 2023 at 07:57 UTC
    > If the "unless" condition results in the "my my_var" not executing, then my_var is never declared in the scope of the subroutine.

    this doesn't make sense

    • declaration is a compile-time effect
    • execution is a run-time effect
    mixing both for a parent scope opens a box full of problems. That's why declaration with post-fix conditions should be avoided.

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery