Suppose I'm not targeting latest Perl versions and their 'trim' built-in, and reluctant to depend on other modules, -- then practically every FAQ or cookbook or tutorial recommend what's "usual" method in test below. Now, I have fair amount of medium-size "records" (variable length and containing white-space somewhere in the middle, NOT as in test below), which may terminate in unpredictable WS sequences, which I want to trim. Performance freak, I've been unsatisfied with the speed and came with "better" version. Then accidentally discovered "unpack" method. Now I'm puzzled if this nice and fast way is kept secret and why :-)
use strict;
use warnings;
use 5.014; # s///r
use Benchmark 'cmpthese';
my @a = map {
( 'a' x 123 ) .
( ' ' x rand 2 ) .
( "\n" x rand 2 )
} 0 .. 999;
cmpthese -1, {
usual => sub { my @ret = map { s/\s*$//r } @a; \@ret },
better => sub { my @ret = map { s/.*\S\K\s*$//sr } @a; \@ret },
unpack => sub { my @ret = map { unpack 'A*', $_ } @a; \@ret },
};
__END__
Rate usual better unpack
usual 159/s -- -88% -95%
better 1284/s 707% -- -56%
unpack 2899/s 1722% 126% --