Skip to content

Commit 433b856

Browse files
Switch to a faster implementation of char_count()
1 parent 8b13b49 commit 433b856

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

diff-so-fancy

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -602,18 +602,13 @@ sub insert_reset_at_line_end {
602602
}
603603

604604
# Count the number of a given char in a string
605+
# https://www.perturb.org/display/1010_Perl_Count_occurrences_of_substring.html
605606
sub char_count {
606-
my ($needle,$str) = @_;
607-
my $len = length($str);
608-
my $ret = 0;
609-
610-
for (my $i = 0; $i < $len; $i++) {
611-
my $found = substr($str,$i,1);
607+
my ($needle, $haystack) = @_;
612608

613-
if ($needle eq $found) { $ret++; }
614-
}
609+
my $count = () = ($haystack =~ /$needle/g);
615610

616-
return $ret;
611+
return $count;
617612
}
618613

619614
# Remove all ANSI codes from a string

0 commit comments

Comments
 (0)