I'm replacing this answer completely. The previous answer started
off with code that it says the user shouldn't use, and the rest
of the code is a bit more complicated.

I've also added some remarks about preserving blank lines, and
stripping leading and trailing whitespace in multi-line strings.


=head2 How do I strip blank space from the beginning/end of a string?

(contributed by brian d foy)

A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. Just
turn that sentence into a regular expression.

      s/^\s+|\s+$//g;

In this regular expression, the alternation matches either at the
beginning or the end of the string since the anchors have a lower
precedence than the alternation. With the C</g> flag, the substitution
makes all possible matches, so it gets both. Remember, the trailing
newline matches the C<\s+>, and  the C<$> anchor can match to the
physical end of the string, so the newline disappears too. Just add
the newline to the output, which has the added benefit of preserving
"blank" (consisting entirely of whitespace) lines which the C<^\s+>
would remove all by itself.

   while( <> )
      {
      s/^\s+|\s+$//g;
      print "$_\n";
      }

For a multi-line string, you can apply the regular expression
to each logical line in the string by adding the C</m> flag (for
"multi-line"). With the C</m> flag, the C<$> matches I<before> an
embedded newline, so it doesn't remove it. It still removes the 
newline at the end of the string.

    $string =~ s/^\s+|\s+$//gm;
    
Remember that lines consisting entirely of whitespace will disappear,
since the first part of the alternation can match the entire string
and replace it with nothing. If need to keep embedded blank lines,
you have to do a little more work. Instead of matching any whitespace
(since that includes a newline), just match the other whitespace.

   $string =~ s/^[\t\f ]+|[\t\f ]+$//mg;

-- 
brian d foy, [EMAIL PROTECTED]

Reply via email to