这个 perl 替换出了什么问题?
my $test = "_.4.1\n";
print $test;
my $docid=4;
$test =~ s/_.$docId.1/_.$docId.0/gm;
print $test
我希望看到:
_.4.1
_.4.0
但我得到:
_.4.1
_.4.1
my $test = "_.4.1\n";
print $test;
my $docid=4;
$test =~ s/_.$docId.1/_.$docId.0/gm;
print $test
I was hoping to see:
_.4.1
_.4.0
But I get:
_.4.1
_.4.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的正则表达式中的
$docId
中有一个大写的I
,但用小写的i
声明它。$docid
不被视为与$docId
相同的变量。 Perl 区分内部变量名的大小写。您应该始终使用
To 防止像这样的简单错误。
另请参阅:为什么使用严格和警告?
You have a capital
I
in$docId
in your regex, but declare it with a lower casei
.$docid
is not considered the same variable as$docId
. Perl differentiates between upper and lower case inside variable names.You should always use
To prevent simple errors like this.
See also: Why use strict and warnings?
Perl 5.10 有一个很好的功能可以让这个问题变得更容易。替换运算符模式部分中的
\K
告诉它不要替换\K
之前的任何内容。这样,您可以使模式找到您想要更改的位,但随后仅替换未更改的部分:我删除了
/g
和/m 标志,因为它们在您的示例中不执行任何操作。
如果您还没有使用 v5.10(它是现在不受支持的版本之一),您可以通过正向后查找获得相同的效果(只要它是恒定宽度模式):
Perl 5.10 has a nice feature that makes this problem easier. a
\K
in the pattern portion of the substitution operator tells it to not replace anything before the\K
. That way, you can make the pattern to locate the bit that you want to change, but then only replace the part that doesn't change:I removed the
/g
and/m
flags because they don't do anything in your example.If you aren't using v5.10 yet (and it's one of the unsupported versions now), you can get the same effect with a positive lookbehind (as long as it's a constant width pattern):
尝试在 perl 中使用 -w 选项
Try using the -w option in perl