Edited by mirod: changed the title to "What happens with empty $1 in regular expressions?"

I have a question about what happens to $1 if it matches neither the empty string nor anything else as in:

$sss = "M9"; $sss =~ m/(\d+)/; print $1; # --> prints 9 $sss = "Mm"; $sss =~ m/(\d+)/; print $1; #--> still prints 9
$1 in this case will still equal 9 rather than undef as would be expected. The following code protects against $1 not resetting from previous matches, but it requires two tests. Does anybody know of any good way to insure $1 resets between matches where we could avoid having to use two tests to determine the status of a match?
$sss = "M9"; if ($sss =~ m/(\d+)/ && $1 ne undef){ print "Value Matched on: $1"; # prints Value Matched on: 9 } $sss = "Mm"; if ($sss =~ m/(\d+)/ && $1 ne undef){ print "Value Matched on: $1"; # if statement is not entered +; prints nothing }
Also, this solution only works if I'm only trying to match on one thing at a time but not if I try to match on multiple items as in the next code snipped:
$sss = "9 9"; if ($sss =~ m/(([A-Za-z]*)(\d*)/ && $1 ne undef){ print "Value Matched on: $1"; # if statement is not entered +; prints nothing }
If the if statement evaluates to true (as it would in this case), there is no way for me to tell whether that happened because of the first or because of the second match.

In reply to What happens with empty $1 in regular expressions? (was: Regular Expression Question) by marcblecher

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.