$h4X4_|=73}{ has asked for the wisdom of the Perl Monks concerning the following question:

I can not figure out why its output changes.

my $nothing = ''; my $list = <<LIST; thing 1 thing 2 $nothing thing 3 thing 4 LIST $list =~ s/\s{2}/2/g; print $list; # output: #thing 1 #thing 22thing23 #thing24

I would like the output.

thing 1 thing 2 thing23 thing24

Replies are listed 'Best First'.
Re: Perl regex. Why does this happen?
by hippo (Archbishop) on Jun 03, 2016 at 09:29 UTC

    The problem is that \s matches any type of whitespace including the newline. If you change your regex line to be:

    $list =~ s/ {2}/2/g;

    it should work as you intend.

Re: Perl regex. Why does this happen?
by BrowserUk (Patriarch) on Jun 03, 2016 at 09:32 UTC
    Why does this happen?

    Because \s match all whitespace chars, including \n; thus \s{2} matches " \n" in your second line.

    Based on the data you've provided, s[(\s{2})(?=\d)][2]g should do what you want.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice. Not understood.
      Based on the data you've provided, s[(\s{2})(?=\d)][2]g should do what you want.
      Or (more simply, IMHO) use \h [horizontal whitespace] instead of \s

        \h added with Perl version 5.10.


        Give a man a fish:  <%-{-{-{-<

Re: Perl regex. Why does this happen?
by Anonymous Monk on Jun 03, 2016 at 10:34 UTC