So my question is that why @array is behaving like a static variable in C language here?It's an artifact of the implementation (and in particular, with an optimization). my has compile-time and run-time effects, and due to the if statement, not all run-time effects happen. As pointed out before, don't rely on it - it may not work like this in the future. And it may not work as expected now either - it won't act like a static C variable if you use recursion:
Note that the second time bar() is called (due to recursion), you do get a different $x - unlike the foo() case.#!/usr/bin/perl use 5.010; use strict; use warnings; sub foo { my $x if 0; say ++$x; } sub bar { my $x if 0; say ++$x; bar() if @_; } foo; foo; bar(1); __END__ Deprecated use of my() in false conditional at ./x line 10. Deprecated use of my() in false conditional at ./x line 15. 1 2 1 1
Since 5.10, there is a warning on my $foo if 0; (at compile time). People have argued there should always be a warning on any my $foo if EXPR or my $foo = EXPR1 if EXPR2; usage, but that hasn't happened, and isn't happening in blead either.
Also since 5.10, if you want a static variable, you can use the state keyword.
In reply to Re: A curious case of of my()
by JavaFan
in thread A curious case of of my()
by fleetingflicker
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |