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:
$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"; $sss =~ m/(\d+)/; print $1; # --> prints 9 $sss = "Mm"; $sss =~ m/(\d+)/; print $1; #--> still prints 9
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 = "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 }
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.$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 }
In reply to What happens with empty $1 in regular expressions? (was: Regular Expression Question) by marcblecher
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |