Wise monks,
I am having a strange and unexpected effect when I create a lexical variable using my in a subroutine, and initialize it conditionally using a 'statement modifier' condition.
In short, when I do this:
sub foo {
...
my $var = "<value>"
if <condition>;
...
}
When I call the subroutine several times, with a changing condition,
it seems that the
my variable keeps its value
from the previous call when the condition is false.
For example:
$ cat my_with_if.pl
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use feature 'signatures';
no warnings 'experimental::signatures';
use Data::Dump qw( pp );
sub foo( $value ) {
say "foo( ", pp( $value ), " )";
my $result = "default"
if not defined $value;
say "\$result after 'my' is ", pp( $result );
$result //= $value;
say "\$result after '//=' is ", pp( $result );
say "";
return $result;
}
foo( $_ )
for (
"call 1.1",
"call 1.2",
"call 1.3",
undef,
"call 2.1",
"call 2.2",
"call 2.3",
);
1;
$ ./my_with_if.pl
foo( "call 1.1" )
$result after 'my' is undef
$result after '//=' is "call 1.1"
foo( "call 1.2" )
$result after 'my' is "call 1.1"
$result after '//=' is "call 1.1"
foo( "call 1.3" )
$result after 'my' is "call 1.1"
$result after '//=' is "call 1.1"
foo( undef )
$result after 'my' is "default"
$result after '//=' is "default"
foo( "call 2.1" )
$result after 'my' is undef
$result after '//=' is "call 2.1"
foo( "call 2.2" )
$result after 'my' is "call 2.1"
$result after '//=' is "call 2.1"
foo( "call 2.3" )
$result after 'my' is "call 2.1"
$result after '//=' is "call 2.1"
Maybe I would have expected that behavior from a static variable, but not from a my variable.
What I would have expected is that the variable would be initialized with undef if the condition is false.
What is the reasoning behind this behavior?
Thank you for helping me understand...!
PS: I know that I can get the undef initialization with
my $var = <condition> ? "<value>" : undef;
if I really want.
I am just curious! :-)