in reply to A curious case of of my()

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:
#!/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
Note that the second time bar() is called (due to recursion), you do get a different $x - unlike the foo() case.

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.

Replies are listed 'Best First'.
Re^2: A curious case of of my()
by fleetingflicker (Initiate) on Apr 05, 2011 at 15:08 UTC
    Thanks JavaFan and LanX.
    Points on compile-time and run-time difference are well taken.
    BTW, in my original code, I do use strict/warning, and knew that separating the declaration and condition statement makes it work as expected. But still knowing a little more about what is going on under the hood is more satisfactory.