perl 精确字符串匹配 [英] perl exact string match

查看:84
本文介绍了perl 精确字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Perl 代码来提示用户是/否答案.如果用户输入的不是是/否,则继续提示.没有其他词是可以接受的.我不知道为什么这段代码不起作用.我用答案nooooooo"进行了测试,我期待它再次提示,但它没有进入 while 循环.

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 this code doesn't work. I tested with answer "noooooo" and I was expecting it to prompt again but it does not enter the while loop.

有人能帮我找出我的错误吗?

Can anyone help find my mistake here?

@files = A, B, C;

foreach $c (@files) {
  if (-e $c  ) { 
     print " $c already exists. Do you want to overwrite?  (yes or no): ";
     chomp ($file_yes_no = <STDIN>);

     while ($file_yes_no !~ m/yes{1}|no{1}/i )  {
         print "$c already exists. Do you want to overwrite?  (yes or no): ";
         chomp ($file_yes_no = <STDIN>);
     }

     if ($file_yes_no =~ m/yes/i ) {
         if (system ("cp -f /home/old_path/ /home/new_path/ == 0) {
             print "$c successfully copied;
         } else {
             die "Error: Copy failed, Check the message above";
         }
     }
 else { print "No files copied\n; }

推荐答案

我只想使用字符串相等运算符 eq 而不是正则表达式.

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

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

如果我想让它不区分大小写,我会先用 lc 转换为小写.

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

你的正则表达式的问题是它会很高兴地匹配任何包含字母yes的字符串.如果你愿意,你可以像这样匹配字符串的开头和结尾:

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

这篇关于perl 精确字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆