如何在perl中将变量用作正则表达式修饰符?

我正在编写一个抽象函数,它将询问用户一个给定的问题,并根据给定的正则表达式验证答案.重复该问题,直到答案与验证正则表达式匹配.但是,我还希望客户端能够指定答案是否必须符合大小写.所以这样的事情:
sub ask {
    my ($prompt,$validationRe,$caseSensitive) = @_;
    my $modifier = ($caseSensitive) ? "" : "i";
    my $ans;
    my $isValid;

    do {
        print $prompt;
        $ans = <>;
        chomp($ans);

        # What I want to do that doesn't work:
        # $isValid = $ans =~ /$validationRe/$modifier;

        # What I have to do:
        $isValid = ($caseSensitive) ?
            ($ans =~ /$validationRe/) :
            ($ans =~ /$validationRe/i);

    } while (!$isValid);

    return $ans;
}

Upshot:有没有办法动态指定正则表达式的修饰符?

解决方法

Upshot: is there any way to dynamically specify a regular expression’s modifiers?

来自perldoc perlre:

“(?adlupimsx-imsx)”
“(?^alupimsx)”
One or more embedded pattern-match modifiers,to be turned on (or
turned off,if preceded by “-“) for the remainder of the pattern or
the remainder of the enclosing pattern group (if any).

This is particularly useful for dynamic patterns,such as those read
in from a configuration file,taken from an argument,or specified in
a table somewhere. Consider the case where some patterns want to be
case-sensitive and some do not: The case-insensitive ones merely need
to include “(?i)” at the front of the pattern.

这给了你一些东西

$isValid = $ans =~ m/(?$modifier)$validationRe/;

在以这种方式接受用户输入时,请务必采取适当的安全预防措施.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...