存储在变量中的 Perl 正则表达式选项

Perl regex option stored in variable

有什么方法可以将正则表达式及其选项存储在标量中吗?就我而言,我有这个:

{
  regex => 'this is'.CONSTANT_STRING'. a regex',
  someOtherKey => someOtherValue
}

匹配时我这样做:

if($line =~ m/$hash->{regex}/i) {
...
}

效果很好。

但我需要的是将选项 /i 存储在正则表达式本身中,这样我就可以做到

if($line =~ $hash->{regex}) {
...
}

但是当我尝试像这样将正则表达式存储在哈希中时:

regex => '/this is a regex/i',

这行不通。我玩过

eval, qr

等等。这有可能做到吗?

您可以使用 qr 和修饰符

regex => qr/this is a regex/i,

或者您可以通过 ?:

内联修饰符
regex => '(?i:this is a regex)',
# or
regex => qr/(?i:this is a regex)/,