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;
}
精彩评论