Search code examples
perlvariable-declarationvariable-initialization

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?


Solution

  • 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++;
    }