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.
|
|---|