Beefy Boxes and Bandwidth Generously Provided by pair Networks chromatic writing perl on a camel
The stupid question is the question not asked
 
PerlMonks  

Re: global match except last one

by jpl (Monk)
on Jul 12, 2011 at 18:16 UTC ( #913975=note: print w/ replies, xml ) Need Help??


in reply to global match except last one

Always curious, I wondered if the apparently complex lookahead logic proposed by ikegami and happy.barney would actually save time over your original approach, ignoring, as we should not, that your original approach made some bold assumptions about where the final underscore would appear. I factored out the final uppercasing to make the code more nearly comparable, and came up with

use Benchmark('countit'); $code = '$str =~ s/(?<=[a-z])(?=[A-Z])/_/g'; $t = countit(5, '$str="BuyACaseOfCamels";' . $code); $count = $t->iters ; print "$count loops of $code\n"; $code = '$str =~ s/([a-z]+)(?=(.?))/ $1 . (length($2) ? "_" : "") /ge' +; $t = countit(5, '$str="BuyACaseOfCamels";' . $code); $count = $t->iters ; print "$count loops of $code\n"; $code = '$str =~ s/([a-z]+)/$1_/g; $str =~ s/_$//'; $t = countit(5, '$str="BuyACaseOfCamels";' . $code); $count = $t->iters ; print "$count loops of $code\n";
I was a bit surprised at the results.
perl ccase.pl 1686588 loops of $str =~ s/(?<=[a-z])(?=[A-Z])/_/g 1194666 loops of $str =~ s/([a-z]+)(?=(.?))/ $1 . (length($2) ? "_" : +"") /ge 1520477 loops of $str =~ s/([a-z]+)/$1_/g; $str =~ s/_$// perl ccase.pl 1793776 loops of $str =~ s/(?<=[a-z])(?=[A-Z])/_/g 1286561 loops of $str =~ s/([a-z]+)(?=(.?))/ $1 . (length($2) ? "_" : +"") /ge 1466174 loops of $str =~ s/([a-z]+)/$1_/g; $str =~ s/_$// perl ccase.pl 1760558 loops of $str =~ s/(?<=[a-z])(?=[A-Z])/_/g 1336044 loops of $str =~ s/([a-z]+)(?=(.?))/ $1 . (length($2) ? "_" : +"") /ge 1492832 loops of $str =~ s/([a-z]+)/$1_/g; $str =~ s/_$//
Over three runs, the counts varied slightly, but happy.barney's code consistently outperformed your original code, and ikegami's code was only slightly less peppy than yours, a fair tradeoff for doing a better job of trimming the final underscore. I, for one, am impressed at how well the regular expression engine can perform.


Comment on Re: global match except last one
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2014-04-20 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (486 votes), past polls