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

Re: Returning _which_ pattern matched...?

by Hofmator (Curate)
on Aug 03, 2001 at 13:47 UTC ( #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?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2023-04-01 07:33 GMT
Find Nodes?
    Voting Booth?

    No recent polls found