Skip to content

Instantly share code, notes, and snippets.

@scottchiefbaker
Created April 30, 2014 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottchiefbaker/296fab782ef8d2e94ffd to your computer and use it in GitHub Desktop.
Save scottchiefbaker/296fab782ef8d2e94ffd to your computer and use it in GitHub Desktop.
use Benchmark qw(cmpthese);
use Getopt::Long;
use strict;
my $short = 0;
my $long = 0;
my $iterations = 3000000;
GetOptions(
"long" => \$long,
"short" => \$short,
"iterations=i" => \$iterations,
);
if (!$long && !$short) {
$short = 1;
}
my $str = "";
if ($short) {
$str = " This is a short string\n";
} elsif ($long) {
$str = " There was nothing so VERY remarkable in that; nor did Alice think it so
VERY much out of the way to hear the Rabbit say to itself, 'Oh dear!
Oh dear! I shall be late!' (when she thought it over afterwards, it
occurred to her that she ought to have wondered at this, but at the time
it all seemed quite natural); but when the Rabbit actually TOOK A WATCH
OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,
Alice started to her feet, for it flashed across her mind that she had
never before seen a rabbit with either a waistcoat-pocket, or a watch
to take out of it, and burning with curiosity, she ran across the field
after it, and fortunately was just in time to see it pop down a large
rabbit-hole under the hedge.\n";
} else {
die("Huh?\n");
}
cmpthese($iterations,
{
with_array => "trim1(\$str)",
dbl_regex => "trim2(\$str)",
reverse => "trim3(\$str)",
regx_rplc => "trim4(\$str)",
}
);
sub trim1 {
if (wantarray) {
my @ret;
foreach (@_) {
push(@ret,scalar(trim($_)));
}
return @ret;
} else {
$_ = shift();
s/^\s+//;
s/\s+$//;
return $_;
}
}
sub trim2 {
$_ = shift();
s/^\s+//;
s/\s+$//;
return $_;
}
sub trim3 {
$_ = shift();
s/^\s+//o;
$_ = reverse;
s/^\s+//o;
$_ = reverse;
}
sub trim4 {
$_ = shift();
s/^\s*(.*?)\s*$/$1/s;
return $_;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment