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

正则表达式 – 在Perl中,有没有${foo [bar]}可能是语法上有效的

发布时间:2020-12-14 06:05:17 所属栏目:百科 来源:网络整理
导读:我正在阅读O’Reilly的Programming Perl,第3版,并且文本指出不应该使用模糊搜索模式/ $foo [bar] /,而应该使用/ ${foo [bar]} /以便Perl不会不要把[bar]误认为是一个角色类.我是否遗漏了某些内容,或者这两个语句在语法上是不正确的,因为它们试图使用裸字字符
我正在阅读O’Reilly的Programming Perl,第3版,并且文本指出不应该使用模糊搜索模式/ $foo [bar] /,而应该使用/ ${foo [bar]} /以便Perl不会不要把[bar]误认为是一个角色类.我是否遗漏了某些内容,或者这两个语句在语法上是不正确的,因为它们试图使用裸字字符串索引到数组中?我已经在网上检查了这本书的勘误表,但在书中找不到任何关于这个错误的提法.是否有一些我忽略的场景,其中代码可能有效?

解决方法

I am reading through O’Reilly’s Programming Perl,3rd Edition,and the text states that instead of using the ambiguous search pattern /$foo[bar]/,one should instead use /${foo[bar]}/ so that Perl doesn’t mistake [bar] for a character class. Am I missing something,or are both of these statements syntactically incorrect due to the fact that they are trying to index into an array using a bareword string?

是的,你错过了一些东西:bar可以是一个函数调用:

$perl -Mstrict -E 'sub bar() { 0 } say "foo" =~ /$ARGV[bar]/ || "FAIL"' foo
FAIL

$perl -Mstrict -E 'sub bar() { 0 } say "foo" =~ /${ARGV[bar]}/ || "FAIL"' foo
1

$perl -MO=Deparse -Mstrict -E 'sub bar() { 0 } say "foo" =~ /${ARGV[bar]}/ || "FAIL"' foo
sub bar () { 0 }
use strict 'refs';
BEGIN {
    $^H{'feature_unicode'} = q(1);
    $^H{'feature_say'} = q(1);
    $^H{'feature_state'} = q(1);
    $^H{'feature_switch'} = q(1);
}
say 'foo' =~ /$ARGV[0]/ || 'FAIL';
-e syntax OK

确切的引用,来自Programming Perl,4th edition的第73页,是:

Within search patterns,which also undergo double-quotish interpolation,there
is an unfortunate ambiguity: is /$foo[bar]/ to be interpreted as /${foo}[bar]/
(where [bar] is a character class for the regular expression),or as /${foo[bar]}/
(where [bar] is the subscript to array @foo)? If @foo doesn’t otherwise exist,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 interpretation with braces as shown earlier. Even if you’re merely prudent,it’s probably not a bad idea.

(编辑:李大同)

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

    推荐文章
      热点阅读