http://www.perlmonks.org?node_id=33920

parsec has asked for the wisdom of the Perl Monks concerning the following question: (strings)

How can I strip an arbitary number of leading spaces from a string?

Originally posted as a Categorized Question.

  • Comment on How can I strip an arbitary number of leading spaces from a string?

Replies are listed 'Best First'.
Re: How can I strip an arbitary number of leading spaces from a string?
by japhy (Canon) on Sep 25, 2000 at 21:04 UTC
    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+.
Re: How can I strip an arbitary number of leading spaces from a string?
by chromatic (Archbishop) on Sep 25, 2000 at 20:15 UTC
    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.}

Re: How can I strip an arbitary number of leading spaces from a string?
by Anonymous Monk on Sep 28, 2004 at 14:04 UTC
    $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.
Re: How can I strip an arbitary number of leading spaces from a string?
by Anonymous Monk on Sep 09, 2004 at 22:20 UTC
    HUGE thanks , dude :))

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.