in reply to Confused by RegEx count
Note that the transliteration is much faster than the other option. Even when the character is variable and we have to use string eval (whip! whip!), it's much faster.
Instead of using substitution with length, you can use global substitution only, as it returns the number of replacements in scalar context. But it's still slower than transliteration:
#! /usr/bin/perl use warnings; use strict; use Benchmark qw{ cmpthese }; my $orig = 'Just another Perl hacker,' x 100; my $str = $orig; my $char = 'r'; my $q = quotemeta $char; sub transliteration { my $count = eval "\$str =~ tr/$q//" } sub length_subst { my $count = length( $str =~ s/[^$q]//rg ) } sub subst { my $count = $str =~ s/$q/$char/g } transliteration() eq length_subst() or die 'Different t-ls'; transliteration() eq subst() or die 'Different t-s'; $orig eq $str or die 'Changed'; cmpthese(-3, { transliteration => \&transliteration, length_subst => \&length_subst, subst => \&subst, }); __END__ Rate length_subst subst transliterati +on length_subst 2833/s -- -91% -9 +7% subst 30244/s 968% -- -7 +0% transliteration 102423/s 3515% 239% +--
Update: Introduced quotemeta to transliteration, too. It didn't change the results significantly.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Confused by RegEx count
by NERDVANA (Priest) on Feb 21, 2024 at 00:06 UTC | |
by choroba (Cardinal) on Feb 21, 2024 at 09:23 UTC | |
by hippo (Archbishop) on Feb 21, 2024 at 09:55 UTC | |
by Danny (Chaplain) on Feb 21, 2024 at 11:41 UTC | |
by choroba (Cardinal) on Feb 22, 2024 at 10:09 UTC | |
by NERDVANA (Priest) on Feb 22, 2024 at 06:17 UTC |