in reply to A curious case of of my()

It's quite simple: Using a my variable without having first executed the my is a bug. By braking that rule, you break the "fourth wall" between the promised behaviour of my and its optimised implementation.

my variables are created at compile time. Executing a my places a directive on the stack that will get executed on scope exit. The directive causes the variable to be cleared (if possible) or replaced (if a reference keeps it alive).

If you want a static variable, use state.

Replies are listed 'Best First'.
Re^2: A curious case of of my()
by LanX (Saint) on Apr 05, 2011 at 16:09 UTC
    Thanks, I forgot about scope-exit behavior...

    Anyway I'm wondering why a post-fix if doesn't force a new scope, IMHO that would solve the problem in a consistent way:

    use strict; use warnings; $a=0; if ($a) { my $z=666; } my $y=666 if $a; print $y; # -> nothing print $z; # -> Global symbol "$z" requires explicit package na +me

    of course treating short circuit and in the same way could cause more complications.

    $a and my $x =666; print $x; # -> nothing

    At least this "it's a new scope" logic could be used to detect "my"-problems at compile-time and throw warnings.

    Cheers Rolf

    UPDATE: short-circuit and

      It wouldn't fix the following:

      foo() and my $x; foo() or my $x; foo() && my $x; foo() || my $x; foo() // my $x; foo() ? my $x : 1;

      Not to mention that some code relies on the current behaviour.

        > Not to mention that some code relies on the current behaviour.

        unlikely, without a new scope this would lead to warnings like

        "my" variable $x masks earlier declaration

        all these cases should be treated alike, (also see update in former post)

        AFAIK post-fix if is always internally translated into a short-circuit and.

        Cheers Rolf