Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Returning _which_ pattern matched...?

by scain (Curate)
on Aug 03, 2001 at 19:02 UTC ( [id://102002]=note: print w/replies, xml ) Need Help??


in reply to Returning _which_ pattern matched...?

You could also consider a more difficult example where you are trying to match lines a data that fall into different "types", so you have different regexs to catch them, even though you are trying to collect the same data regardless of the form (clear as mud so far, right?).

Let's just say that you end up with three different regexs. You deside to write three different ones because it would have made the single combined regex a god-awful mess. Good. Now, if you use Hofmator's suggestion, you'll get something like this:

if ($string =~ /re1/ || $string =~ /re2/ || $string =~ /re3/)
where $1 will be populated with what you are looking for, but you still may not know which of re1, 2 or 3 matched. In this case I would use a bigger if. If you want to know which regex matched, it is presumably because you want to do different things with the results. So put them all in if..else's:
if ( $string =~ /re1/ ) { #do thing 1 } elsif ( $string =~ /re2/ ) { #do thing 2 } elsif ( $string =~ /re3/ ) { #do thing 3 }
It is bulkier than other suggestions, but I suspect it is a more generally useful answer to your question.

Scott

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (8)
As of 2024-04-18 06:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found