in reply to Conditional initialization of lexical (my) variables

You found a bug that many people had found before and that was finally fixed in 5.30. Read for example this article on Effective Perl Programming to get the background.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Conditional initialization of lexical (my) variables
by hv (Prior) on May 10, 2023 at 16:54 UTC

    What are you suggesting is fixed in 5.30? I was not aware of any change in behaviour around this (which I understood was unfixable due to back-compat), and indeed I see the same output for the OP's script with 5.30, 5.32, 5.34 and 5.36.

      perl -wE 'BEGIN { print $] } my $x if 0' 5.037003 This use of my() in false conditional is no longer allowed at -e line +1.
      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

        Ah ok, that appears to be a quite specific case being caught, I would guess during constant folding:

        % /opt/v5.36.0/bin/perl -wlE 'BEGIN { print $] } my $x if $ARGV[0]' 0 5.036000 % /opt/v5.36.0/bin/perl -wlE 'BEGIN { print $] } my $x if $ARGV[0]' 1 5.036000 %
        not the same thing

        This my $x if 0 is definitely a bug, because constant folding shouldn't allow a lexical to be declared.

        But the OP has a condition which is only checked at run-time, while the declaration happens at compile-time.

        This means the new variable will not be overwritten with an init-value if the condition is false.

        The deeper issue is that postfix-conditions have no own scope, the problem is non-existent for if ($bool) {my $x = ... }

        Not sure if this qualifies as a bug or a weird feature.

        But a warning should happen in any case if a declaration happens before a postfix condition, because of the broken symmetry to prefix conditions.

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

Re^2: Conditional initialization of lexical (my) variables
by muthm (Sexton) on May 10, 2023 at 14:12 UTC
    Thank you for your answer!
    I also noticed that I have already sent the same question before (id:11151504)!
    Shame on me! I'm getting old!

    But thanks a lot for the article link!
    The article makes things very clear! :-)