gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:01:19 25 4
gpt4 key购买 nike

今天遇到了a twitter post告诉我另一个神秘的 Perl 行为。有人可以告诉我以下脚本中的第三个语句有什么问题吗?我正在 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 .

关于使用只有 3 位索引的列表元素的正则表达式替换不能按我预期的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49492181/

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