简体   繁体   中英

Perl ignore whitespace on replacement side of regular expression substitution

Suppose I have $str = "onetwo" .

I would like to write a reg ex substitution command that ignores whitespace (which makes it more readable):

$str =~ s/
          one
          two
         /
          three
          four
         /x

Instead of "threefour" , this produces "\\nthree\\nfour\\n" (where \\n is a newline). Basically the /x option ignores whitespace for the matching side of the substitution but not the replacement side. How can I ignore whitespace on the replacement side as well?

s{...}{...} is basically s{...}{qq{...}}e . If you don't want qq{...} , you'll need to replace it with something else.

s/
   one
   two
/
   'three' .
   'four'
/ex

Or even:

s/
   one
   two
/
   clean('
      three
      four
   ')
/ex

A possible implementation of clean :

sub clean {
    my ($s) = @_;
    $s =~ s/^[ \t]+//mg;
    $s =~ s/^\s+//;
    $s =~ s/\s+\z//;
    return $s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM