http://qs321.pair.com?node_id=1171509


in reply to Re^3: Get a known substring from a string
in thread Get a known substring from a string

I'm really astonished by your approach of using 1+index(...) - it had not occurred to me to use index that way in an expression to check for presence.

I've been using it that way for as long as I can remember. This turns up 50+ of my uses here with the earliest being in September 2002 which is only a few months after I started coming here.

Adding the one has another benefit when doing searches in a loop:

##do something with $p - 1 while $p = 1 + index( $haystack, $needle, $ +p );

That of automatically moving the start point along after each match.

You have to remember to subtract 1 when using the match point; but that's no more onerous than remembering to increment it.

I had thought there once was an optimization that turned constant regular expressions without anchors or quantifiers into an index lookup...

That optimisation is there, and can be even quicker than index but you have to code it exactly correctly for it to kick in::

$s = 'the quick brown fox jumps over the lazy dog'; cmpthese -1,{ a => q[ if( $s =~ m[(lazy)]){ $found=$1 } ], b => q[ $found = 'lazy' if 1+index( $s, 'lazy' ); ], c => q[ $found = 'lazy' if $s =~ 'lazy'; ], };; Rate a b c a 577066/s -- -77% -79% b 2492720/s 332% -- -11% c 2791311/s 384% 12% -- [0]{} Perl>

Unfortunately, it doesn't generalise. Even using a variable instead of literal means some of that performance gain is lost:

$s = 'the quick brown fox jumps over the lazy dog'; $x = 'lazy'; cmpthese -1,{ a => q[ if( $s =~ m[($x)]){ $found = $1 } ], b => q[ $found = $x if 1 + index( $s, $x ); ], c => q[ $found = $x if $s =~ $x ], };; Rate a c b a 449697/s -- -79% -82% c 2167332/s 382% -- -12% b 2462877/s 448% 14% -- $s = 'the quick brown fox jumps over the lazy dog'; $x = 'lazy'; cmpthese -1,{ a => q[ if( $s =~ m[($x)]){ $found = $1 } ], b => q[ $found = $x if 1 + index( $s, $x ); ], c => q[ $found = $x if $s =~ $x ], };; Rate a c b a 459542/s -- -79% -80% c 2184810/s 375% -- -6% b 2318112/s 404% 6% --

The nature of the type of work I do means that I learnt early on to only start the regex engine if I needed regex.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.