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/;
在以这种方式接受用户输入时,请务必采取适当的安全预防措施.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。