in reply to More efficient way to truncate long strings of the same character
One is a generalization of what you've already been given and uses the substitution operator with an eval. It therefore uses the regular expression engine. The other uses a character count and substr instead. The former makes better use of language features in Perl. The latter is readily portable to language with weak or no support of regular expressions so long as they have decent string handling otherwise.
I have no idea which is faster. A toy-sized solution like this really isn't worth benchmarking unless it's in a hotspot in a larger program. If backreferences are really a big thing to worry about, then the longer version might be worthwhile. The rest of the regex engine is pretty darn fast, though, so I imagine the substitution is faster whether or not backreferences are a speed issue.
Contrasting the two solutions does show off the power of Perl's regular expression handling and the operators that work with it. The longer of these two subs only handles a specific case, but the substitution operator could do something entirely different with the change of just a few keystrokes. Behold, the power of chee... er, Perl.
#!/usr/local/bin/perl use strict; use warnings; my $foo = 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiii' . 'jjjjjjjjjj122333444455555666666777777788888888999999999!'; for my $longest ( 1 .. 5 ) { my $bar = max_run_1 ( $longest, $foo ); print 'max_run_1: ' . $bar . "\n"; $bar = max_run_2 ( $longest, $foo ); print 'max_run_2: ' . $bar . "\n"; } sub max_run_1 { my $max = $_[0]; my $len = length $_[1]; ### loop prelude my $char = substr $_[1], 0, 1; my $count = 1; my $new_string = $char; my $at = 1; while ( $at < $len ) { my $old_char = $char; $char = substr $_[1], $at++, 1; if ( $char eq $old_char ) { next if $count >= $max; $count++; } else { $count = 1; } $new_string .= $char; } return $new_string; } sub max_run_2 { my $max = $_[0]; ( my $new_string = $_[1] ) =~ s/(.)\1{$max,}/$1 x $max/eg; return $new_string; }
|
|---|