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

How should that be implemented? I think this should work just like all forms of the built-in chomp except it should remove more than trailing newlines. However, the argumentless form doesn't seem to work (doesn't propagate the lvalue context on the caller's $_) as I would expect it should. What's the right way of falling back to the caller's lvalue $_ if there's no arguments?
sub trim { @_ = ($_) if not @_; # doesn't work foreach (@_) { s/^\s*//; s/\s*$//; s/\n\z//s; } return wantarray? @_ : $_[0]; }

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: Re: Fastest (Golfish) way to strip whitspace off ends.
by BrowserUk (Patriarch) on Jul 02, 2003 at 17:21 UTC

    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


Re: Re: Re: Fastest (Golfish) way to strip whitspace off ends.
by Enlil (Parson) on Jul 02, 2003 at 22:32 UTC
    Halley,

    I am curious as to what s/\n\z//s would actually substitute that the previous two substitutions already had not.

    AFAICT, the \n\z would match any newlines before the end of the string, which should have been already taken care of s/\s*$//; (as \n is matched by \s) should have captured anyway (i might be missing something here, so please correct me if i am wrong.)

    Also, I believe that \s+ should be faster(more efficient) in this case than \s* .

    -enlil