[英]concatenating strings in Perl substitute expression
I have a string having a repeating pattern, and I want to replace each occurrence of such pattern with another string. 我有一个具有重复模式的字符串,并且我想用另一个字符串替换每次出现的这种模式。 The replacement string is formed by concatenating a set of other strings.
替换字符串是通过串联一组其他字符串形成的。 An example is as below.
一个例子如下。 I first tried concatenating using the
.
我首先尝试使用进行串联
.
operator as shown. 如图所示。
But the output contained the dots themselves, so Perl does not treat it as an operator, but a literal .
但是输出本身包含点,因此Perl不会将其视为运算符,而是文字
.
. 。
#!/usr/bin/perl
use warnings;
use strict;
my $start = 'not-so-';
my $end = '-but-a-little-bad';
my $string = 'I am a good boy. Infact I am a very good boy';
print "Before: $string\n";
>>>> $string =~ s/(good)/$start.$1.$end/g;
print "Later : $string\n";
So I removed the .
所以我删除了
.
s, and my statement became $string =~ s/(good)/$start$1$end/g;
s,我的语句变成
$string =~ s/(good)/$start$1$end/g;
, and the output is as per expectation. ,并且输出符合预期。 But, I feel a statement like this might cause maintenance issues later.
但是,我觉得这样的声明稍后可能会导致维护问题。
My question: Is there a better way of concatenating strings other than this? 我的问题:除此以外,还有没有更好的串联字符串的方法?
You notation 你符号
$string =~ s/(good)/$start$1$end/g;
is good. 很好。 If you prefer, you can also write
如果您愿意,也可以写
$string =~ s/(good)/$start . $1 . $end/ge;
but it's totally equivalent. 但这是完全等效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.