in reply to substitute leading whitespace

It doesn't work for two reasons.

1) When using /g, Perl won't match from the same point within the string twice, so ^ will only match on the first pass.

2) Your use of ^ ensures that no character other than the first can possibly be replaced.

Use \G instead of ^ to match where the last pass of /g left off. It behaves like ^ on the first pass.

my $string = ' this is a string'; $string =~ s/\G\s/:/g; print("$string\n"); # :::this is a string

Update: Rephrased (2) since it wasn't clear.

Replies are listed 'Best First'.
Re^2: substitute leading whitespace
by tlm (Prior) on Jun 10, 2005 at 10:46 UTC

    ikegami, maybe I'm misunderstanding your second reason, but I don't think it is correct, because it implies that, under the /g modifier, prior substitutions affect subsequent matches, but consider the following variant of the original example:

    my $s = ' this is a string'; ( my $t = $s ) =~ s/(?<!\w)\s/X/g; print $t, $/; __END__ XXXthis is a Xstring
    If I understood your second reason correctly, according to it the printout would have been:
    X Xthis is a Xstring
    because after the first substitution the second space no longer matches the first part of the s///.

    the lowliest monk

      You've just demonstrated my first point. My second point explained why the regexp wouldn't work even in the absense of the behaviour.

      Less abstractly, I was tring to explain that matching the beginning of the string (^ when not under /m) is useless under </code>/g</code>. It's the same as if /g wasn't there. I rephrased my post to this effect.

        You've just demonstrated my first point. My second point explained why the regexp wouldn't work even in the absense of the behaviour. Less abstractly, I was tring to explain that matching the beginning of the string (^ when not under /m) is useless under </code>/g</code>.

        Heh, that's a neat trick! First, delete the text a post refers to, and then offer an (unfalsifiable) interpretation of what that post is saying. Cool!

        the lowliest monk