or if you're dealing exact strings, substr/rindexmy $string = "abababa"; $string = reverse $string; $string =~ s/b/x/; $string = reverse $string; print $string,$/;
I'm not sure which is better (and that may vary from different perl versions, and/or size of string), so whats left is to benchmark.my $string = "abababa"; my $ri = rindex( $string, 'b' ); substr( $string, $ri, 1) = 'x'; print $string,$/;
update: and here is my benchmark. sexeger comes out on top in two different versions of perl
use Benchmark 'cmpthese'; my $sref = { neglook => sub { my $string = "abababa"; $string =~ s/(b)(?!.*b)/x/; return; }, rindex => sub { my $string = "abababa"; my $ri = rindex( $string, 'b' ); substr( $string, $ri, 1) = 'x'; return; }, sexeger => sub { my $string = "abababa"; $string = reverse $string; $string =~ s/b/x/; $string = reverse $string; return; }, }; cmpthese( 3_000_000, $sref ); __END__ perl5.8.4 Rate neglook rindex sexeger neglook 523195/s -- -21% -36% rindex 659776/s 26% -- -19% sexeger 813670/s 56% 23% -- perl5.6.2 Rate neglook rindex sexeger neglook 719252/s -- -19% -20% rindex 888889/s 24% -- -1% sexeger 901442/s 25% 1% --
UPDATE: And of course, I hadn't taken my own advice. Here is the updated benchmark:
use Benchmark 'cmpthese'; use strict; use warnings; my $sref = { neglook => sub { my $string = "abababa"; $string =~ s/(b)(?!.*b)/x/; return; }, neganch => sub { my $string = "abababa"; $string =~ s/(b)(?!.*b)$/x/; return; }, rindex => sub { my $string = "abababa"; my $ri = rindex( $string, 'b' ); substr( $string, $ri, 1) = 'x'; return; }, sxedni => sub { my $string = "abababa"; $string = reverse $string; my $ri = index( $string, 'b' ); substr( $string, $ri, 1) = 'x'; $string = reverse $string; return; }, sexeger => sub { my $string = "abababa"; $string = reverse $string; $string =~ s/b/x/; $string = reverse $string; return; }, }; $|=1; print "Revving up my CPU"; for( 1 .. 3 ){ my $foo = 0; $foo++ for 1 .. 3_000_000; $foo-- for 1 .. 3_000_000; print '.'; } print "\n"; cmpthese( 3_000_000, $sref ); __END__ perl5.8.4 Rate sxedni neglook rindex sexeger neganch sxedni 505221/s -- -6% -26% -39% -79% neglook 534855/s 6% -- -22% -35% -77% rindex 685714/s 36% 28% -- -17% -71% sexeger 824176/s 63% 54% 20% -- -65% neganch 2369668/s 369% 343% 246% 188% -- perl5.6.2 Rate sxedni neglook rindex sexeger neganch sxedni 596303/s -- -17% -33% -33% -80% neglook 716503/s 20% -- -19% -19% -76% rindex 884695/s 48% 23% -- 0% -71% sexeger 884695/s 48% 23% 0% -- -71% neganch 3003003/s 404% 319% 239% 239% --
In reply to Re: RE - match from right
by PodMaster
in thread RE - match from right
by bangers
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |