Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Regular Expression Question

by ZZamboni (Curate)
on Feb 28, 2001 at 06:32 UTC ( [id://61260]=note: print w/replies, xml ) Need Help??


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

The problem is that the $1, $2, etc. variables only get set if the regular expression matches. /(\d+)/ does NOT match "Mm", so no assignment occurs. What you need to do is to check whether there is a match before using the positional variables, like this:
if ($sss =~ /(\d+)/) { # use $1 as you wish } else { # don't! }
Interestingly, your last code snippet will do the right thing if you remove the part after the && (and an extra opening parenthesis you seem to have there), because $1 and $2 will only be used when there is a match, and in that case they will contain either the strings they matched, or undef if their respective subexpressions didn't match anything.

--ZZamboni

Replies are listed 'Best First'.
Re: Re: Regular Expression Question
by japhy (Canon) on Feb 28, 2001 at 19:28 UTC
    No, $1 will not be undef if the match fails. The only time they are undefined is when a match has not yet been done, or a match does not contain a captured pattern for that variable:
    #!/usr/bin/perl -w if ("abc" =~ /(\w+)/, 1) { print "abc => $1\n" } { print "local: $1\n"; if ("ghi" =~ /\w+/, 1) { print "ghi => $1\n" } if ("def" =~ /(\w+)/, 1) { print "def => $1\n" } if ("[=]" =~ /(\w+)/, 1) { print "[=] => $1\n" } } print "general: $1\n"; __END__ abc => abc local: abc Use of uninitialized value at regexes line 6. ghi => def => def [=] => def general: abc
    However, a failed match returns false, so if you removed the , 1's from each of those, you wouldn't see the line for "=".

    japhy -- Perl and Regex Hacker
      I agree completely with you, and that's what I meant, that if the regex does not match, $1 is not modified in any way (neither set or unset). But your example made it way clearer than any explanation :-)

      --ZZamboni

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://61260]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-03-28 17:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found