使用只有3位索引的列表元素进行正则表达式替换不能像我预期的那样工作

前端之家收集整理的这篇文章主要介绍了使用只有3位索引的列表元素进行正则表达式替换不能像我预期的那样工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
今天我遇到 a twitter post告诉我另一个神秘的Perl行为.有人可以告诉我以下脚本中的第3个语句有什么问题吗?我正在寻找perldoc中相关的文档部分.

#!/usr/bin/perl

$x[1]    = "foo"; $_ = "foo"; s/$x[1]/bar/;    print "$_\n";
$x[10]   = "foo"; $_ = "foo"; s/$x[10]/bar/;   print "$_\n";
$x[100]  = "foo"; $_ = "foo"; s/$x[100]/bar/;  print "$_\n";
$x[1000] = "foo"; $_ = "foo"; s/$x[1000]/bar/; print "$_\n";

__END__
bar
bar
foo
bar

似乎perl解释器倾向于将$x与[100]分开.

$x[100] = 'foo';
$_ = 'foo';
s/${x}[100]/bar/;
print "$_\n";

编辑

谢谢你们.我在Camel Book中找到了一个文档,它建议
与@ fred-gannet完全相同.启发式的因素是数字
括号中的字符出现和修剪策略.

https://books.google.com/books?id=xx5JBSqcQzIC&lpg=PR1&pg=PA65#v=onepage&q&f=false

Within search patterns,which also undergo double-quotish interpolation,
there is an unfortunate ambiguity: is /$foo[bar]/ to be interpolated as
/${foo}[bar]/ (where [bar] is character class for the regular expression)
or as /${foo[bar]}/ (where [bar] is the subscript to array @foo)? If
@foo doesn’t otherwise exists,it’s obvIoUsly a character class. If @foo
exists,Perl takes a good guess about [bar],and is almost always right.† If
it does guess wrong,or if you’re just plain paranoid,you can force the
correct interpolation with braces as shown earlier. Even if you’re merely
prudent,it’s probably not a bad idea.

https://rt.perl.org/Public/Bug/Display.html?id=133027#txn-1542459

The code is in S_intuit_more().

https://github.com/Perl/perl5/blob/823ba440369100de3f2693420a3887a645a57d28/toke.c#L4207-L4217

if (*s == '$')
    weight -= 3;
else if (isDIGIT(*s)) {
    if (s[1] != ']') {
    if (isDIGIT(s[1]) && s[2] == ']')
        weight -= 10;
    }
    else
    weight -= 100;
}
Zero(seen,256,char);

在日语中有一个逻辑的解释. (出奇!)

https://8-p.info/perl-interpolation/

解决方法

显然,perl在数组索引和正则表达式字符集(例如/ [a-z] /)之间变得混乱.行为不一致. 100至998的指数似乎受此影响.请使用脚本 perlbug报告错误.

猜你在找的正则表达式相关文章