Perl Bug 5 - my $var = val if (..) doesn't work properly


If a variable is declared "my" and then conditional set with a trailing if, the value is *not* undefined if the condition isn't met. Here's some example code:

sub joe {
  # These should arguably be the same:
  #my $x; $x = 42 if (0);
  my $x = 42 if (0);

  print "x: $x\n";
  $x = 1001;    # This setting should be lost
}

joe();
joe();
The first line declares the variable and then conditionally either sets the variable or leaves it as undef. The second line declares the variable, and conditionally either sets the variable or leaves it as junk (most likely the previous my value)

You could argue that the "my" becomes part of the condition, so if the condition is false, then the variable isn't scoped as a my variable, but if that was the case the script should get an error from "use strict"

Otherwise, according to 'man perlsub' the my variable should be undef:

Here's a more interesting example that demonstrates what's causing the bug:

sub joe { my $x = 42 if (0);  return \$x; }

my $y = joe();
my $z = joe();
$$y = 12;
printf "Hey: $z is $$z\n";

This is, of course, demonstrating that joe() now has an unintentional static variable without using any variables outside it's own scope.


The current stance from perl.org is (according to Peter Scott):