On Aug 6, Mooney Christophe-CMOONEY1 said:

>That would do it.  Without the 's' in front of the regex, it doesn't know
>you're trying to search and replace.
>
>The divide error is odd, and shouldn't be happening, but try this instead:
>       s(\s*)()g

The divide-by-zero error was because writing

  $foo =~ /regex//g;

makes Perl think you're doing

  ($foo =~ /regex/) / g;

And 'g' has a numerical value of 0.

And now for the "far more than you ever wanted to know about whitespace"
thing.

To remove ALL whitespace from a string, efficiently, you should use
either:

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

or:

  $string =~ tr/\n\r\t\f //d;

You'll notice I advocate s/\s+//g and NOT s/\s*//g.  The reason is because
I don't like making Perl do a lot of work, and because frankly, the \s*
solution is wrong.  Why is it wrong?

BECAUSE \s* MATCHES EVERYWHERE.

Huh?  Yeah.  \s* can match anywhere.  In fact, it matches in FIVE places
in the string "jeff", even though there's NO WHITESPACE in that string at
all.  In fact, it matches five times BECAUSE there's no whitespace.

\s* means "zero or more whitespace characters".  There are zero
whitespaces before the "j", and before the "e", and before the "f", and
before the second "f", and then after the "f".

If you wanted to change all chunks of whitespace to "_", then using

  s/\s+/_/g

would be the right approach.  Using

  s/\s*/_/g

would definitely be the WRONG approach.  Try it on a string like
"jeff" and see what happens.

Removing leading whitespace is done most simply with

  s/^\s+//;

That says it all.  "Remove one or more whitespaces at the beginning of the
string."  That's all.  If you WANT to be crafty, you can write

  s/\s*//;

which will also work, but it will probably make people wonder for a long
time why it DOES work.

Removing trailing whitespace is often done with

  s/\s+$//;

However, I found terrible inefficiencies with that approach which I hope
to resolve in an upcoming release of Perl.  You can use it, or you can use
the sexeger approach:

  $_ = reverse;
  s/^\s+//;
  $_ = reverse;

That's all for now.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **


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

Reply via email to