in reply to Re: Re: Fastest (Golfish) way to strip whitspace off ends.
in thread Fastest (Golfish) way to strip whitspace off ends.

Here's a couple of ways, but neither is necessarially the best way.

sub trim { @_ = ($_) if not @_; foreach my $s (@_) { $s =~ s/^\s*//; $s =~ s/\s*$//; $s =~ s/\n\z//s; } return wantarray? @_ : $_[0]; }

Or

sub trim { @_ = ($_) if not @_; local $_; foreach (@_) { s/^\s*//; s/\s*$//; s/\n\z//s; } return wantarray? @_ : $_[0]; }

I think that the problem with your implementation was that you were stomping on the aliasing of $_ by re-using the global $_ implicitly in your foreach loop. Using either a my'd var or localising $_ after the assignment to @_ but before the foreach loop seems to fix the problem, though I have a gut feel that there is probably a better way.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller