The reason this, and many other variables are persistent, is that they're "global special variables", which is to say, Main::variable_name has some magic to it (in this case, Main::$3 is the third captured match). The upshot is, once $3 gets set by a match, it can't go away by going out of scope (Ignore that, it was wrong. Match variables are implicitly dynamically scoped for extra magic, as ig points out in the reply below.) perlvar could provide some further enlightenment on the subject (or might bury you in details). As the other answers have said, you need to test that the match succeeded before you use the result.

In reply to Re: Problem with regexp or saved match variable. by ssandv
in thread Problem with regexp or saved match variable. by steve077

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.