我想确保变量被插值,因为它们在 perl 正则表达式中。宁愿避免在整个代码执行过程中很少需要该变量的“ifs”级联中绑定到其他变量。我怎么能确保我使用了这个变量?
use strict;
use warnings FATAL => "all";
$_="botherther";
my $bo = "bother";
if (/^$bother$/) { # want to consider just $bo here!
print("Undestood regex as /($bo)ther/.\n");
} else {
print("Couldnt discern variable.\n");
}
my $bi = { bo => "the" };
if (/^bo$bi->{bo}[r]ther$/) { # now, $bi->{bo} only
print("Discerned /bo($bi->{bo})[r]/\n");
} else {
print("Couldnt discern variable.\n");
}
我无法找到将变量正确包装在正则表达式中的方法。当然,我可以只my $bi_resolved = $bi->{bo}
用空值(如[]
or ()
)填充正则表达式,但这感觉不像是一个合适的分隔符。
为了清楚起见:
- 我想扩展
$bo
为在第一个匹配项中bother
获取字符串。/botherther/
- 我想在第二场比赛中再次扩展
$bi->{bo}
到the
get 。<bo><the><[r]ther>
/botherther/
- 重要的是,为了这个上下文,我不在乎转义
\Q
和\E
“我假设变量中永远没有元字符”。
我已经搜索了问题,阅读了文档,但找不到答案。包装${}
对我不起作用(那是试图取消引用东西)。所以,在搜索时,我觉得我只是对着错误的树吠叫......简直令人难以置信,没有人需要围绕 perlmonks 或 stackoverflow 提出类似的问题。我可能只是在这里寻找错误的关键字。:/