What is wrong in “my $foo = $x if $y” syntax?

后端 未结 1 910
天命终不由人
天命终不由人 2021-01-05 01:22

In my last question here, @amon gave an great answer. However, he told too:

First of all, please don\'t do my $foo = $x if $y. You get u

相关标签:
1条回答
  • 2021-01-05 01:44

    His wording was actually a bit laxer. That wording is actually mine. Let's start with the documentation: (Emphasis in original)

    NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

    To be more precise, the problem is using a lexical variable when its my may not have been executed.

    Consider:

    # Usage:
    #   f($x)  # Store a value
    #   f()    # Fetch and clear the stored value
    
    sub f {
       my $x if !@_;
       if (@_) {
          $x = $_[0];
       } else {
          return $x;
       }
    }
    
    f('abc');
    say "<", f(), ">"   # abc
    

    This is obviously not the documented behaviour of my.

    Because the above construction I was see in really many sources in the CPAN

    That code is buggy.

    0 讨论(0)
提交回复
热议问题