Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Returning _which_ pattern matched...?

by scain (Curate)
on Aug 03, 2001 at 19:02 UTC ( #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.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2023-03-22 21:33 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (60 votes). Check out past polls.