这个 perl 替换出了什么问题?

发布于 2024-12-21 06:02:13 字数 210 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

薄荷港 2024-12-28 06:02:13

您的正则表达式中的 $docId 中有一个大写的 I,但用小写的 i 声明它。 $docid 不被视为与 $docId 相同的变量。 Perl 区分内部变量名的大小写。

您应该始终使用

use strict;
use warnings;

To 防止像这样的简单错误。

另请参阅:为什么使用严格和警告?

You have a capital I in $docId in your regex, but declare it with a lower case i. $docid is not considered the same variable as $docId. Perl differentiates between upper and lower case inside variable names.

You should always use

use strict;
use warnings;

To prevent simple errors like this.

See also: Why use strict and warnings?

梦晓ヶ微光ヅ倾城 2024-12-28 06:02:13

Perl 5.10 有一个很好的功能可以让这个问题变得更容易。替换运算符模式部分中的 \K 告诉它不要替换 \K 之前的任何内容。这样,您可以使模式找到您想要更改的位,但随后仅替换未更改的部分:

use v5.10;
use strict;
use warnings;

my $test = "_.4.1";
say $test;

my $docId=4;
$test =~ s/_\.$docId\.\K1/0/;

say $test;

我删除了 /g/m 标志,因为它们在您的示例中不执行任何操作。

如果您还没有使用 v5.10(它是现在不受支持的版本之一),您可以通过正向后查找获得相同的效果(只要它是恒定宽度模式):

use strict;
use warnings;

my $test = "_.4.1";
print "$test\n";

my $docId = 4;
$test =~ s/(?<=_\.$docId\.)1/0/;

print "$test\n";

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:

use v5.10;
use strict;
use warnings;

my $test = "_.4.1";
say $test;

my $docId=4;
$test =~ s/_\.$docId\.\K1/0/;

say $test;

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):

use strict;
use warnings;

my $test = "_.4.1";
print "$test\n";

my $docId = 4;
$test =~ s/(?<=_\.$docId\.)1/0/;

print "$test\n";
沉溺在你眼里的海 2024-12-28 06:02:13

尝试在 perl 中使用 -w 选项

_.4.1
Use of uninitialized value $docId in regexp compilation at test.pl line 4.
_.4.1


$docid != $docId;

Try using the -w option in perl

_.4.1
Use of uninitialized value $docId in regexp compilation at test.pl line 4.
_.4.1


$docid != $docId;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文