Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
Alan Turing Avatar asked Nov 24 '25 09:11

Alan Turing


1 Answers

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;
}
like image 189
ikegami Avatar answered Nov 26 '25 22:11

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!