in reply to Dot star okay, or not?

Cirollo,

I would be more careful to delimit what you want to keep, i.e., $string =~ s/^\s*(\S.*?\S)\s*$/$1/; Scott

Update: OK, I agree with several other posters indicating that $scalar =~ s/^\s*//; $scalar =~ s/\s*$//; is better and certainly faster.

Replies are listed 'Best First'.
Re: Re: Dot star okay, or not?
by Hofmator (Curate) on Jul 05, 2001 at 20:40 UTC

    This just makes things unnecessarily more complicated, scain. The original version is absolutely equivalent to yours and shorter to write - thus easier to understand. $string =~ s/^\s*(.*?)\s*$/$1/;

    Some further explanation: The starting \s* eats up all whitespaces (because its greedy). Then (.*?) starts capturing and the first character must be \S (or the end of the string for something matching /^\s*$/). Due to its non-greediness the (.*?) advances slowly one character at a time, always trying to match afterwards the rest of the pattern (\s*$) and backtracks if not successful. So all trailing whitespaces are for sure eaten up by the greedy \s* at the end of the pattern leaving a \S as the last character in the capturing brackets.

    The solution with two replaces given by many other monks is preferable as it

    • is quicker
    • doesn't get caught on embedded newlines (as . matches by default everything but a newline) - if you only want to remove space at the beginning and end of the string
    • is easily adaptable to remove all leading and trailing whitespaces on a slurped file:
      $file =~ s/^\s+//mg; $file =~ s/\s+$//mg;

    -- Hofmator