Contributed by Zombie parsec
on Sep 25, 2000 at 20:00 UTC
Q&A
> strings
Answer: How can I strip an arbitary number of leading spaces from a string? contributed by japhy There is no need to use s/^\s*//. This
will waste time on strings with no leading space.
Use s/^\s+// at all times -- it obviously
won't do anything if there's no whitespace to match.
A general rule of thumb is that s/X*//
is slower than s/X+//, and in cases where
the RHS (right-hand side) is something OTHER than
"", chances are you really do mean X+. | Answer: How can I strip an arbitary number of leading spaces from a string? contributed by chromatic Use a regex with a quantifier. Use this one if you're not sure there will be any spaces at the start of the string:
$string =~ s/^\s*//;
Use this one if you know there will be at least one:
$string =~ s/^\s+//;
{QA Editors note: As japhy pointed out, the "+" quantifier is preferable over the "*" quantifier, even if it's unknown whether the string being tested has leading whitespace or not. With s/^\s+//;, strings lacking leading whitespace simply will be passed over. Furthermore, the "+" quantifier is faster than the "*" quantifier.} | Answer: How can I strip an arbitary number of leading spaces from a string? contributed by Anonymous Monk $string =~ s/^\s+//gm;
this will start at the beginning and only continue as long as there is whitespace left at the beginning of the string. | Answer: How can I strip an arbitary number of leading spaces from a string? contributed by Zombie parsec OK, silly me, that didn't take very long to figure
out:
$string = <>;
$string =~ s/ *//;
Edit by Corion
This answer is maybe sufficient, if every string contains at least one space. If one of your strings does not contain a space, it will remove spaces from the middle or the end of the string. Please have a look at chromatics post for a correct answer.
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|