加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:01:16 所属栏目:百科 来源:网络整理
导读:今天我遇到 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[1
今天我遇到 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报告错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读