gpt4 book ai didi

regex - 在 Perl 正则表达式替换中使用 $1 和\1 有什么区别?

转载 作者:行者123 更新时间:2023-12-04 01:40:43 24 4
gpt4 key购买 nike

我正在调试一些代码,想知道 Perl 正则表达式替换中的 $1 和\1 之间是否有任何实际区别

例如:

my $package_name = "Some::Package::ButNotThis";

$package_name =~ s{^(\w+::\w+)}{$1};

print $package_name; # Some::Package

下面这行在功能上看起来是等价的:
$package_name =~ s{^(\w+::w+)}{\1};

这两种说法之间有细微的差别吗?它们在不同版本的 Perl 中表现不同吗?

最佳答案

首先,您应该在开发时始终使用 warnings:

#!/usr/bin/perl

use strict; use warnings;

my $package_name = "Some::Package::ButNotThis";

$package_name =~ s{^(\w+::\w+)}{\1};

print $package_name, "\n";

输出:
\1 better written as $1 at C:\Temp\x.pl line 7.

When you get a warning you do not understand, add diagnostics:

C:\Temp> perl -Mdiagnostics x.pl\1 better written as $1 at x.pl line 7 (#1)    (W syntax) Outside of patterns, backreferences live on as variables.    The use of backslashes is grandfathered on the right-hand side of a    substitution, but stylistically it's better to use the variable form    because other Perl programmers will expect it, and it works better if    there are more than 9 backreferences.

Why does it work better when there are more than 9 backreferences? Here is an example:

#!/usr/bin/perl

use strict; use warnings;

my $t = (my $s = '0123456789');
my $r = join '', map { "($_)" } split //, $s;

$s =~ s/^$r\z/\10/;
$t =~ s/^$r\z/$10/;

print "[$s]\n";
print "[$t]\n";

输出:
C:\Temp> x][9]

If that does not clarify it, take a look at:

C:\Temp> x | xxd0000000: 5b08 5d0d 0a5b 395d 0d0a                 [.]..[9]..

See also perlop:

The following escape sequences are available in constructs that interpolate and in transliterations …

\10 octal is 8 decimal. So, the replacement part contained the character code for BACKSPACE.

NB

Incidentally, your code does not do what you want: That is, it will not print Some::Package some package contrary to what your comment says because all you are doing is replacing Some::Package with Some::Package without touching ::ButNotThis.

You can either do:

($package_name) = $package_name =~ m{^(\w+::\w+)};

或者
$package_name =~ s{^(\w+::\w+)(?:::\w+)*\z}{$1};

关于regex - 在 Perl 正则表达式替换中使用 $1 和\1 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3068236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com