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.


In reply to Re: A curious case of of my() by JavaFan
in thread A curious case of of my() by fleetingflicker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.