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

前端之家收集整理的这篇文章主要介绍了如何在perl中将变量用作正则表达式修饰符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个抽象函数,它将询问用户一个给定的问题,并根据给定的正则表达式验证答案.重复该问题,直到答案与验证正则表达式匹配.但是,我还希望客户端能够指定答案是否必须符合大小写.所以这样的事情:
  1. sub ask {
  2. my ($prompt,$validationRe,$caseSensitive) = @_;
  3. my $modifier = ($caseSensitive) ? "" : "i";
  4. my $ans;
  5. my $isValid;
  6.  
  7. do {
  8. print $prompt;
  9. $ans = <>;
  10. chomp($ans);
  11.  
  12. # What I want to do that doesn't work:
  13. # $isValid = $ans =~ /$validationRe/$modifier;
  14.  
  15. # What I have to do:
  16. $isValid = ($caseSensitive) ?
  17. ($ans =~ /$validationRe/) :
  18. ($ans =~ /$validationRe/i);
  19.  
  20. } while (!$isValid);
  21.  
  22. return $ans;
  23. }

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.

这给了你一些东西

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

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

猜你在找的Perl相关文章