perl exact string match

前端 未结 3 1134
忘掉有多难
忘掉有多难 2021-01-19 13:30

I have following Perl code to prompt user for yes/no answer. If the user enters anything else than yes/no, keep prompting. No other word is acceptable. I don\'t know why thi

3条回答
  •  [愿得一人]
    2021-01-19 13:48

    I would just use the string equality operator eq instead of a regex.

    if( $file_yes_no eq 'yes' ) ...
    

    If I wanted it case insensitive I'd first convert to lowercase with lc.

    The problem with your regex is it will happily match any string containing the letters yes sequentially. If you wish, you can match the start and end of the string like this:

    if ($file_yes_no =~ m/^yes$/i ) ...
    

    But I personally prefer the first option.

    Oh, I missed the first part... Hmmmm. Same deal, if you must use regex.

    m/^(yes|no)$/i
    

    Once again I'd be more inclined to avoid regex

提交回复
热议问题