sir*_*lol -3 perl if-statement
下面是我的代码,基本上如果答案是"Y",那么脚本会运行一条消息,如果它是其他东西然后它关闭.
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Run Code Online (Sandbox Code Playgroud)
如果你问的话,Perl会告诉你究竟是什么问题.只需在代码中添加"使用警告"即可.
#!/usr/bin/perl
use warnings;
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Run Code Online (Sandbox Code Playgroud)
然后运行它,给出:
$ ./y
Do you wish to run Program? [Y/N]:Y
Argument "Y" isn't numeric in numeric eq (==) at ./y line 6, <> line 1.
Argument "Y\n" isn't numeric in numeric eq (==) at ./y line 6, <> line 1.
COOOL
Run Code Online (Sandbox Code Playgroud)
如果你添加"使用诊断",它会更好.
$ ./y
Do you wish to run Program? [Y/N]:Y
Argument "Y" isn't numeric in numeric eq (==) at ./y line 7, <> line 1 (#1)
(W numeric) The indicated string was fed as an argument to an operator
that expected a numeric value instead. If you're fortunate the message
will identify which operator was so unfortunate.
Argument "Y\n" isn't numeric in numeric eq (==) at ./y line 7, <> line 1 (#1)
COOOL
Run Code Online (Sandbox Code Playgroud)
如果让Perl帮助您找到错误,Perl中的编程会容易得多.
删除换行符.==
是数字相等,你需要的字符串eq
.
chomp($answer);
if($answer eq "Y") {
Run Code Online (Sandbox Code Playgroud)