#!/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);
在日语中有一个逻辑的解释. (出奇!)