gpt4 book ai didi

perl 精确字符串匹配

转载 作者:行者123 更新时间:2023-12-04 02:41:22 25 4
gpt4 key购买 nike

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

谁能帮我在这里找到我的错误?

@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 而不是正则表达式。

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

如果我想要它不区分大小写,我会首先使用 lc 转换为小写。

你的正则表达式的问题是它会很高兴地匹配任何包含字母 yes 的字符串。如果你愿意,你可以像这样匹配字符串的开头和结尾:
if ($file_yes_no =~ m/^yes$/i ) ...

但我个人更喜欢第一种选择。

哦,我错过了第一部分......嗯。同样的交易,如果你必须使用正则表达式。
m/^(yes|no)$/i

再一次,我更倾向于避免使用正则表达式

关于perl 精确字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14699822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com