【发布时间】:2015-05-15 18:42:56
【问题描述】:
在 Perl 中:
my $string = "This is a test";
say "String matches" if $string =~ /this is a test/; # Doesn't print
say "String sort of matches" if string =~ /this is a test/i; # Prints
在 RE 匹配的末尾添加 i 标志会导致匹配忽略大小写。
我有一个程序,我在其中指定要在单独的数据文件中匹配的正则表达式。这工作正常。但是,我希望能够扩展它并能够指定在检查匹配时使用的正则表达式标志。
但是,在 Perl 中,这些 RE 标志不能是标量:
my $re_flags = "i";
my $string = "This is a test";
say "This sort of matches" if $string =~ /this is a test/$re_flags;
这会导致:
Scalar found where operator expected at ,,, line ,,, near "/this is a test/$re_flags"
(Missing operator before $re_flags?)
syntax error at ... line ..., near "/this is a test/$re_flags"
Execution of ... aborted due to compilation errors.
在计算正则表达式时,有没有办法使用存储在标量变量中的 RE 标志?
我知道我可以使用eval:
eval qq(say "This worked!" if \$string =~ /this is a test/$re_flags;);
但我想要一种更好的方法。
【问题讨论】:
-
@ThisSuitIsBlackNot,您建议的答案本身就是重复的
-
@ikegami 我选择了那个,因为我认为它(问题和答案)比它[据称]重复的帖子更符合这个问题。据我所知,重复链没有任何问题。
-
无论如何,ikegami 给出的答案要好得多。我想避免整个
eval如果匹配。 -
@DavidW。只有我链接的帖子中的最后一个答案使用
eval,并且该答案被否决为-2。其他三个答案都显示使用相同的语法 ikegami,尽管我同意 ikegami 的答案更好。