我是Perl的新手.我有一个编写Perl程序的任务,该程序接受来自命令行的可数字,然后生成其复数形式.我在下面编写了以下代码,它没有显示编译错误.当我从命令行执行它时:(例如perl plural.pl),它会提示我输入名词,然后输入任何名词作为输入,复数形式是相同的.它不执行剩余的if语句.
例如,如果我输入单词"cat",则复数被生成为"cats".但是当我输入"教堂"这个词时,复数就会产生"教堂","飞"就像"飞翔".
这是代码:
#!/usr/bin/perl
$suffix1 = 's';
$suffix2 = 'es';
$suffix3 = 'ies';
print "Enter a countable noun to get plural: ";
$word = <STDIN>;
chomp($word);
if(substr $word, -1 == 'b' or 'd' or 'c' or 'g' or 'r' or 'j' or 'k' or 'l' or 'm' or 'n' or 'p' or 'q' or 'r' or 't' or 'v' or 'w' or 'e' or 'i' or 'o' or 'u') {
$temp = $word.$suffix1;
print "The plural form of the word \"$word\" is: $temp \n";
}
elsif (substr $word, -1 == 's' or 'sh' or 'ch' or 'x' or 'z') {
$temp = $word.$suffix2;
print "The plural form of the word \"$word\" is: $temp \n";
}
elsif (substr $word, -1 == 'y') {
chop($word);
$temp = $word.$suffix3;
print "The plural form of the word \"$word\" is: $temp \n";
}
Run Code Online (Sandbox Code Playgroud)
你能帮我把代码执行三个语句吗?
首先,始终使用use strict; use warnings;.
字符串使用eq而不是比较==.
substr $word, -1 eq 'b'意思是substr $word, (-1 eq 'b')你的意思substr($word, -1) eq 'b'.如果省略函数调用的问题,你将面临很多问题.
substr($word, -1) eq 'b' or 'd'意思是一样的(substr($word, -1) eq 'b') or ('d').'d'总是如此.你需要使用substr($word, -1) eq 'b' or substr($word, -1) eq 'd'.(最好保存substr $word, -1一个变量以避免重复这样做.)
substr $word, -1绝不会等于ch或sh.
匹配运算符使这很容易:
if ($word =~ /[bdcgrjklmnpqrtvweiou]\z/) {
...
}
elsif ($word =~ /(?:[sxz]|[sc]h)\z/) {
...
}
elsif ($word =~ /y\z/) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1534 次 |
| 最近记录: |