Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl "my $bar if 0;" vs "my $bar = undef if 0;"

The following code will return an error,

$ perl -E'sub foo { my $bar if 0; $bar++ }'
This use of my() in false conditional is no longer allowed at -e line 1.

But this code

$ perl -E'sub foo { my $bar = undef if 0; $bar++ }'

Does not return an error. Is there any difference between these two forms?

like image 762
NO WAR WITH RUSSIA Avatar asked Dec 30 '25 12:12

NO WAR WITH RUSSIA


1 Answers

my has a compile-time effect and a run-time effect, and you don't want to use a my variable without first having its run-time effect.

Since the problematic situation is using a my variable under different conditions than it was declared, there is no difference between your two snippets. Both should be avoided.

To create a persistent variable scoped to a sub, you can use

{
   my $bar = 0;
   sub foo {
      return $bar++;
   }
}

or

use feature qw( state );  # 5.10+

sub foo {
   state $bar = 0;
   return $bar++;
}
like image 69
ikegami Avatar answered Jan 01 '26 08:01

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!