There may well be a bug there, but it might also be a result of this:
  my ($cat) = @_ if @_;
If @_ is empty, $cat will have the value it had the last time you were in the block. This is due to the way perl reuses scratchpads on block entry. Every sub (not every block, mind, but every sub) has a scratchpad associated with it, with space for all the my'd variables reserved in it. If, at runtime, you enter that sub and the default scratchpad isn't in use (because of recursive calls, for example) perl will use the default scratchpad. This saves on time, as the assumption is you won't be recursive and you will enter a sub more than once over the run of the program. Reusing the scratchpad means no time spent to allocate memory each time through.

The interesting bit is that initialization--giving the variables in the scratchpads values--is a runtime thing. Perl doesn't give a default to variables that have values assigned as part of the my, as that'd be a waste of time as well. (Why assign a default that's going to be immediately overwritten?) But your assignment is conditional, and in some cases it won't happen. That means that in those cases where the condition on the initial assignment isn't met no assignment happens at all. And, since perl's reusing scratchpads, you'll just get whatever was in there from the last time around.

Needless to say, this is often not what you want.


In reply to Re: 'my' buggy... by Elian
in thread 'my' buggy... by december

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.