Scripting Perl替换为变量

Scripting Perl替换为变量,scripting,perl,regex,Scripting,Perl,Regex,我正在尝试替换字符串中的一个单词。单词存储在一个变量中,因此我自然会这样做: $sentence = "hi this is me"; $foo=~ m/is (.*)/; $foo = $1; $sentence =~ s/$foo/you/; print $newsentence; 但这不起作用 有没有办法解决这个问题?为什么会发生这种情况?必须替换相同的变量,否则未设置$newsentence,Perl不知道替换什么: $sentence = "hi this is me"; $foo

我正在尝试替换字符串中的一个单词。单词存储在一个变量中,因此我自然会这样做:

$sentence = "hi this is me";
$foo=~ m/is (.*)/;

$foo = $1;
$sentence =~ s/$foo/you/;
print $newsentence;
但这不起作用


有没有办法解决这个问题?为什么会发生这种情况?

必须替换相同的变量,否则未设置
$newsentence
,Perl不知道替换什么:

$sentence = "hi this is me";
$foo = "me";
$sentence =~ s/$foo/you/;
print $sentence;
如果要将
$sentence
与其以前的值保持一致,可以将
$sentence
复制到
$newsentence
并执行替换,该替换将保存到
$newsentence

$sentence = "hi this is me";
$foo = "me";
$newsentence = $sentence;
$newsentence =~ s/$foo/you/;
print $newsentence;

您首先需要将
$sence
复制到
$newsentence

$sentence = "hi this is me";

$foo = "me";

$newsentence = $sentence;
$newsentence =~ s/$foo/you/;

print $newsentence;

即使是小脚本,也请“使用严格”和“使用警告”。您的代码段使用$foo和$newsentence而不初始化它们,“strict”会捕捉到这一点。请记住,“=~”用于匹配和替换,而不是赋值。还要注意,Perl中的正则表达式在默认情况下不是word绑定的,因此您得到的示例表达式将$1设置为'is me','is'匹配了'this'的尾部

假设您试图将字符串从“hi this is me”转换为“hi this is you”,您将需要类似以下内容:

my $sentence = "hi this is me";
$sentence =~ s/\bme$/\byou$/;
print $sentence, "\n";

在正则表达式中,“\b”是单词边界,“$”是行尾。在您的示例中,只执行“s/me/you/”也可以,但是如果您有一个像“this is merry old me”这样的字符串,它将变成“this is yourry old me”,则可能会产生意想不到的效果。

Perl允许您将字符串插入正则表达式,正如许多答案已经显示的那样。在该字符串插值之后,结果必须是有效的正则表达式

在最初的尝试中,您使用了match操作符
m//
,它会立即尝试执行匹配。您可以在其位置使用正则表达式引号运算符:

$foo = qr/me/;
您可以绑定到该目录或插入该目录:

$string =~ $foo;
$string =~ s/$foo/replacement/;

您可以在中阅读更多关于
qr/

这方面的惯用perl可能是
$old=“me-You”$chg=“我”;($new=$old)=~s/$chg/you/;打印$new
——注意
($new=$old)=~s//作为一个概念分组进行复制和更改。始终使用
使用strict;使用警告。它会指出您使用了错误的变量名。