How do I use a variable as a regex modifier in Perl?

前端 未结 4 2023
予麋鹿
予麋鹿 2020-12-11 17:13

I\'m writing an abstraction function that will ask the user a given question and validate the answer based on a given regular expression. The question is repeated until the

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 17:44

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

    From 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.

    Which gives you something along the lines of

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

    Just be sure to take the appropriate security precautions when accepting user input in this way.

提交回复
热议问题