Adriano Rodrigues Ferreira wrote:
> 
> My problem is:
> 
> Given a (multiline) string, I want a function which remove all leading and trailing
> white-space (as given by \s).
> 
> Examples:
>         "       abbds   \n   sass       "   =>   "abbds   \n   sass"
>         "        a      "               => "a"
>         "   \n first phrase \n second phrase \n \n" => "first phrase \n second 
>phrase"
>         "     \017 a   " => "\017 a"
>         "    " => ""
> 
> These also show the following cases:
> * space in between goes on unchanged,
> * also characters which are not space and which does not match \w (like \017), must
>         remain unchanged too,
> * strings with only spaces map into the empty string
> 
> I have tried
> 
> sub trim {
>         my ($text) = @_;
>         $text =~ m<^\s*(?=\S)(.*)(?=\S)\s*$>s;
>         return $2;
> }
> 
> The rationale is: (1) scan leading spaces, (2) match a zero-length assertion when
> a non space is encountered, (3) scan everything collecting into $2 until
> (4) a zero-length assertion for a non space is matched, (5) followed
> by trailing spaces. Then I catch $2.
> 
> But it does not work. If I change the pattern to
>         ^\s*\b(.*)\b\s*$
> and return $1, it works except for cases like "  \017 a   ".
> I'm not sure I have understood how to use (?= ). Is \b equivalent
> to (?=\w) ?
> 
> I would like the solution as concise and simple as possible.


Have you looked at the solution in the FAQ?

perldoc -q "strip blank space"


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

       Although the simplest approach would seem to be:

           $string =~ s/^\s*(.*?)\s*$/$1/;

       Not only is this unnecessarily slow and destructive, it
       also fails with embedded newlines.  It is much faster to
       do this operation in two steps:

           $string =~ s/^\s+//;
           $string =~ s/\s+$//;

       Or more nicely written as:

           for ($string) {
               s/^\s+//;
               s/\s+$//;
           }

       This idiom takes advantage of the `foreach' loop's alias­
       ing behavior to factor out common code.  You can do this
       on several strings at once, or arrays, or even the values
       of a hash if you use a slice:

           # trim whitespace in the scalar, the array,
           # and all the values in the hash
           foreach ($scalar, @array, @hash{keys %hash}) {
               s/^\s+//;
               s/\s+$//;
           }



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to