我正在编写一个抽象函数,它将询问用户一个给定的问题,并根据给定的正则表达式验证答案.重复该问题,直到答案与验证正则表达式匹配.但是,我还希望客户端能够指定答案是否必须符合大小写.所以这样的事情:
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/;
在以这种方式接受用户输入时,请务必采取适当的安全预防措施.