Thanks to everyone for their input!

So I've tried out many of the methods, first making sure that each
works as I intended it.
Which is, I'm not concerned with multi-line text, just single line
data.  That said, I have noted
that I should use \A and \z in general over ^ and $.

I wrote a 176 byte string for testing, and ran each method 1,000,000
times to time
the speed.  The winner is: 3 regexp, using tr for intra-string
spaces.  I found I could
make this even faster using a pointer to the variable versus passing
in the variable
as a local input parameter, modifying, then returning it.  (In all
cases, my goal is
to write a sub for general use anywhere I want it, so I wrote each
possibility as
a sub.  There ARE cases where I need to compare the the original
string with the
"cleaned" string, but I can deal with that as need be with local
variables.)

1ST PLACE - THE WINNER:  5.0s average on 5 runs

# Limitation - pointer
sub fixsp5 {
${$_[0]}=~tr/ \t\n\r\f/ /s;
${$_[0]}=~s/\A //;
${$_[0]}=~s/ \z//;
}

2nd PLACE - same as above, but with local variables - 6.0s average on
5 runs

sub fixsp4 {
my ($x)=...@_;
$x=~tr/ \t\n\r\f/ /s;
$x=~s/\A //;
$x=~s/ \z//;
return $x;
}

[ QUESTION - any difference using    my $x=shift;    ??? ]

3rd PLACE - 3 way tie, my method, either as variable in, change in
place, or pointer - 17.0s average

sub fixsp0 {
my ($x)=...@_;
$x=~s/^\s+//;
$x=~s/\s+$//;
$x=~s/\s+/ /g;
return $x;
}

# Limitation: pointer
sub fixsp1 {
${$_[0]}=~s/^\s+//;
${$_[0]}=~s/\s+$//;
${$_[0]}=~s/\s+/ /g;
}

# Limitation: change in place
sub fixsp2 {
$_[0]=~s/^\s+//;
$_[0]=~s/\s+$//;
$_[0]=~s/\s+/ /g;
}

4TH PLACE - 20.0s average on 5 runs (did not try change in place or as
pointer)

sub fixsp6 {
my ($x)=...@_;
s/\s+\z//, s/\A\s+//, s/\s+/ /g, for $x;
return $x;
}

5TH PLACE - DEAD LAST! (or DFL in some parlance) - 62.0s average on 3
runs

sub fixsp3 {
my ($x)=...@_;
$x=~s/^(\s+)|(\s+)$//g;
$x=~s/\s+/ /g;
return $x;
}

Any and all comments welcome.

David


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to