$text =~ s/^\s+|\s+$//g;
This can be hopelessly inefficient (the regexp engine gets bogged down in the middle of the string, looking for hypothetical end anchors). The longer the string gets, the better it is to write:
$text =~ s/^\s+//g;
$text =~ s/\s+$//g;
Consider the following, somewhat pathological cases:
#! /usr/local/bin/perl -w
use Benchmark qw/:all/;
`
my $long = ' aaa bbb ccc' . (' ' x 100).'ggg hhh ';
my $short = ' aaa bbb ccc ddd eee fff ggg hhh ';
sub one_long {
my $s = $long;
$s =~ s/^\s+|\s+$//g;
$s;
}
sub one_short {
my $s = $short;
$s =~ s/^\s+|\s+$//g;
$s;
}
sub two_long {
my $s = $long;
$s =~ s/^\s+//g;
$s =~ s/\s+$//g;
$s;
}
sub two_short {
my $s = $short;
$s =~ s/^\s+//g;
$s =~ s/\s+$//g;
$s;
}
print "tests:\n";
{
no strict 'subs';
print "$_ [", &$_, "]\n"
for qw/one_long one_short two_long two_short/;
}
cmpthese(
shift || 1000,
{
one_long => \&one_long,
one_short => \&one_short,
two_long => \&two_long,
two_short => \&two_short,
}
);
__PRODUCES__
tests:
one_long [aaa bbb ccc
+ ggg hhh]
one_short [aaa bbb ccc ddd eee fff ggg hhh]
two_long [aaa bbb ccc
+ ggg hhh]
two_short [aaa bbb ccc ddd eee fff ggg hhh]
Benchmark: timing 100000 iterations of one_long, one_short, two_long,
+two_short...
one_long: 8 wallclock secs ( 7.13 usr + 0.00 sys = 7.13 CPU) @ 14
+019.72/s (n=100000)
one_short: 2 wallclock secs ( 1.62 usr + 0.00 sys = 1.62 CPU) @ 61
+835.75/s (n=100000)
two_long: 1 wallclock secs ( 0.62 usr + 0.00 sys = 0.62 CPU) @ 16
+0000.00/s (n=100000)
two_short: 0 wallclock secs ( 0.63 usr + 0.00 sys = 0.63 CPU) @ 15
+8024.69/s (n=100000)
Rate one_long one_short two_short two_long
one_long 14020/s -- -77% -91% -91%
one_short 61836/s 341% -- -61% -61%
two_short 158025/s 1027% 156% -- -1%
two_long 160000/s 1041% 159% 1% --
It should be obvious from the results that it's good insurance to write it in the two s/// form and be done with it :)