Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Returning _which_ pattern matched...?

by Hofmator (Curate)
on Aug 03, 2001 at 13:47 UTC ( [id://101930]=note: print w/replies, xml ) Need Help??


in reply to Returning _which_ pattern matched...?

bikeNomad already answered your question, just let me elaborate a little bit on some of your statements

  • (Honestly, I don't know why; this was a suggestion from a more experienced engineer, ...)
    you should always try to see the logic behind such statements. In your case of matching different pattern against a string, this solution might be more effective (to shorten my code, consider $string to be in $_): if (/($m1)/ || /($m2)/ || /($m3)/) This is quicker then your big regex if you know that $m1 will be more frequent than $m2 (which in turn is more frequent than $m3).
    The explanation is simple, in your case the regex engine has to check all three patterns for every position in the string. With the || construct, the checking of the $m2 and $m3 pattern might not be necessary. So you see, it pays off, to know your data. (Remark: In general, the size of a regex says nothing about its execution time, only the compile time increases. Execution time depends on the content!)
  • If speed is an issue, consider the /o modifier and qr//. Furthermore you might try to lowercase the whole string and the patterns instead of matching /i. And studying the string might also help.
  • For all this advice, the 'correct' way can be found out by using Benchmark on some real data. By doing that you can find out yourself what works when and don't have to rely on some 'experts'.
  • The FAQs/resources don't offer any aid, and other Perl wizards say it can't be done.
    Just to show you TMTOWTDI - not that I recommend this if (/($m1(?{$match=1})|$m2(?{$match=2})|$m3(?{$match=3}))/) { ... you can execute code from within the regex ... and this is a really bad example of this powerful feature - but a way to do it :)

-- Hofmator

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 19:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found