为什么我的终端只允许我输入一些东西然后代码停止?

  • 本文关键字:然后 代码 终端 允许我 perl
  • 更新时间 :
  • 英文 :


我试图运行这个脚本,我做得又差又快。有人可以指出我正确的方向或纠正我吗?当我运行脚本时,它说"你想用你的购物清单做什么?"然后,它让我输入一些东西,然后它就停止了。平原停靠点

use Term::ANSIColor;
Menu();
sub Menu {
print "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn";
print "What would you like to do with your shopping list? n";
print colored("> Add Item n", 'bold blue');
print colored("> Look at list n", 'bold blue');
print colored("> Reset n", 'bold red');
print colored("> Quit n", 'bold red');
print "> ";
my $a = <STDIN>;
lc $a;
chomp $a;
if ($a == "quit") {
open (my $fh, '>>', 'list.txt') or die "Couldn't find file!";
while(<FH>) { 
print $_; 
}
close $fh;
} else {
Action();
}
}
sub Action {
if ($a == "add" || "add item") {
open(my $fh, '>>', 'list.txt') or die "Couldn't find file!";
print "What would you like to add to the list?n";
print "> ";
my $i = <>;
lc $i;
chomp $i;
print "n";
print "> ";
print FH $i;
print 
close $fh;
} elsif ($a == "list" || "look at list") {
open (my $fh, '>>', 'list.txt') or die "Couldn't find file!";
while(<FH>) { 
print $_; 
} 
close $fh;
} elsif ($a == "reset"){
open (my $fh, '>>', 'list.txt') or die "Couldn't find file!";
print FH colored("Shopping list", 'bold underline');
close $fh;
} else {
print "Unknown command! Try again.";
Menu();
}
}

Perl 有两组比较运算符。

那些看起来像数学(==!=>等(的会做一个数字比较。

看起来像单词(eqnegt等(的单词会进行字符串比较。

您有以下各项:

if ($a == "quit") {
...
if ($a == "add" || "add item") {
...
} elsif ($a == "list" || "look at list") {
...
} elsif ($a == "reset"){

所有这些都在进行数字比较。您需要将所有==更改为eq.

此外,这不是您认为的那样:

if ($a == "add" || "add item") {

我想你的意思是:

if ($a eq "add" or $a eq "add item") {

此外,$a是 Perl 中的一个特殊变量。请不要在一般代码中使用它。变量命名很重要。您的变量应称为$action

更新:同样值得指出的是,如果你的代码中有use warnings(你应该始终在Perl代码中包含use warnings(,那么你会看到警告,告诉你你的代码有问题。

$ perl -Mwarnings -e'$action = "x"; print "yes" if $action == "quit"'
Argument "quit" isn't numeric in numeric eq (==) at -e line 1.
Argument "x" isn't numeric in numeric eq (==) at -e line 1.

相关内容

最新更新