Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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 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 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 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://913975]
[1nickt]: Is it possible to disable it?
[Discipulus]: if you mean [download] after the code it is there 1nickt
[1nickt]: yes, Corion sees it too, and I see it when not logged in.
[Corion]: I think you can disable download links in your settings?
[1nickt]: Looking in settings to see if I disabled it in my profile ...
[1nickt]: There is "Don;t show embedded d/l links" in Display settings. It is unchecked.
[1nickt]: Oh, there is a minimum lines setting!

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2017-05-23 18:21 GMT
Find Nodes?
    Voting Booth?