muthm has asked for the wisdom of the Perl Monks concerning the following question:
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:
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.sub foo { ... my $var = "<value>" if <condition>; ... }
$ 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.
PS: I know that I can get the undef initialization with
if I really want.my $var = <condition> ? "<value>" : undef;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Conditional initialization of my-variables
by kcott (Archbishop) on Apr 07, 2023 at 00:56 UTC | |
Re: Conditional initialization of my-variables (runtime)
by LanX (Saint) on Apr 06, 2023 at 23:37 UTC | |
by ikegami (Patriarch) on May 11, 2023 at 08:31 UTC | |
Re: Conditional initialization of my-variables
by eyepopslikeamosquito (Archbishop) on Apr 07, 2023 at 00:58 UTC | |
by Bod (Parson) on Apr 07, 2023 at 19:26 UTC | |
by eyepopslikeamosquito (Archbishop) on Apr 07, 2023 at 23:32 UTC | |
by LanX (Saint) on Apr 08, 2023 at 12:57 UTC | |
by LanX (Saint) on Apr 07, 2023 at 19:40 UTC | |
by Bod (Parson) on Apr 08, 2023 at 17:55 UTC | |
by LanX (Saint) on Apr 08, 2023 at 18:24 UTC | |
| |
A reply falls below the community's threshold of quality. You may see it by logging in. |