Can someone explain this perl snippet?

  • A+
for my $n (1, 2) {   sub_example(); }  sub sub_example {   my $bar = 1 if 1 == 2;   if ($bar) {      print "hahha, you see/n";   }   else {      $bar = 1;   } } 

So my question is why is $bar defined in the second loop iteration?


You're taking advantage of a strange bug (officially deprecated and slated to become a fatal error in 5.30), which involves declaring a lexical (my) variable in a statement with a statement-modifier conditional which is false.

The reason that this happens is because my $bar = 1; basically has two functions. It has a compile-time function, which is to reserve space in the lexical pad for a variable, and to associate $bar with that space; and it has a run-time function, which is to assign 1 to $bar whenever control flow reaches the my statement (a statement like my $foo; without the assignment also has these two effects, except it assigns undef at runtime).

When you govern the statement with a false conditional like my $bar = 1 if 1 == 2;, the compile-time function stays exactly the same, but the run-time function is prevented from running using the false condition, which means that whatever value was in that storage is re-used, without being assigned fresh each time the code reaches that point. This gives an effect almost, but not exactly, like using a state variable. It's a cool trick, but not recommended for any serious use, and as I've mentioned, it will be fatalized in an upcoming release of perl, which is another reason not to rely on it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: