marcblecher has asked for the wisdom of the Perl Monks concerning the following question:
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 }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regular Expression Question
by chromatic (Archbishop) on Feb 28, 2001 at 06:27 UTC | |
|
Re: Regular Expression Question
by ZZamboni (Curate) on Feb 28, 2001 at 06:32 UTC | |
by japhy (Canon) on Feb 28, 2001 at 19:28 UTC | |
by ZZamboni (Curate) on Feb 28, 2001 at 19:40 UTC | |
|
Re: Regular Expression Question
by dsb (Chaplain) on Feb 28, 2001 at 21:41 UTC | |
by danger (Priest) on Feb 28, 2001 at 22:25 UTC | |
by merlyn (Sage) on Feb 28, 2001 at 22:30 UTC | |
by danger (Priest) on Feb 28, 2001 at 23:29 UTC | |
by chipmunk (Parson) on Mar 01, 2001 at 00:40 UTC | |
by dsb (Chaplain) on Mar 01, 2001 at 00:47 UTC | |
by chipmunk (Parson) on Mar 01, 2001 at 01:05 UTC | |
by tye (Sage) on Mar 01, 2001 at 00:57 UTC |