为什么 perl 中的 unless 函数不起作用
why the unless function in perl isn't working
我正在编写一个简单的 perl 脚本,它根据用户给出的小时数计算付款,该程序不得允许超过 500 小时的付款,但必须允许女性最多 600 小时,并且我正在使用 unless 函数但它不起作用它允许女性超过 600 小时。
这是我使用的代码
print("Enter your working hours");
$hours=<stdin>;
print("Enter your gender");
$gender=<stdin>;
chomp($gender);
unless($gender ne "f" && $hours>=600){
print("Your have earned ",$hours*10," Birr \n");
}
else{
unless($hours>=500){
print("Your have earned ",$hours*10," Birr \n");
}
else{
print("You have worked beyond the payable hrs!");
}
}
分解一下。
it allows more than 600 hrs for females.
让我们尝试一些测试数据。
$gender = "f";
$hours = 750;
将其输入到您的测试中:
unless($gender ne "f" && $hours>=600){
用值替换变量
unless("f" ne "f" && 750>=600){
将测试转换为布尔值
unless(false && true){
解析逻辑运算符
unless(false);
这意味着它运行表达式。
你在用双重否定混淆自己。
尝试通过将逻辑分开并避免否定来简化逻辑。
my $allowedHours = 500;
if ($gender eq "f") {
$allowedHours = 600;
}
if ($hours <= $allowedHours) {
# report
} else {
# error
}
我总是喜欢在数据结构中预先陈述我的假设。
my %allowable_hours = (
m => 500, # I'm assuming that's your other gender :-)
f => 600,
);
unless (exists $allowable_hours{$gender}) {
die "$gender is an unknown gender\n";
}
if ($hours <= $allowable_hours{$gender}) {
# report
} else {
# error
}
更容易编辑允许的时间和添加新的性别(如果有必要的话)。
我正在编写一个简单的 perl 脚本,它根据用户给出的小时数计算付款,该程序不得允许超过 500 小时的付款,但必须允许女性最多 600 小时,并且我正在使用 unless 函数但它不起作用它允许女性超过 600 小时。
这是我使用的代码
print("Enter your working hours");
$hours=<stdin>;
print("Enter your gender");
$gender=<stdin>;
chomp($gender);
unless($gender ne "f" && $hours>=600){
print("Your have earned ",$hours*10," Birr \n");
}
else{
unless($hours>=500){
print("Your have earned ",$hours*10," Birr \n");
}
else{
print("You have worked beyond the payable hrs!");
}
}
分解一下。
it allows more than 600 hrs for females.
让我们尝试一些测试数据。
$gender = "f";
$hours = 750;
将其输入到您的测试中:
unless($gender ne "f" && $hours>=600){
用值替换变量
unless("f" ne "f" && 750>=600){
将测试转换为布尔值
unless(false && true){
解析逻辑运算符
unless(false);
这意味着它运行表达式。
你在用双重否定混淆自己。
尝试通过将逻辑分开并避免否定来简化逻辑。
my $allowedHours = 500;
if ($gender eq "f") {
$allowedHours = 600;
}
if ($hours <= $allowedHours) {
# report
} else {
# error
}
我总是喜欢在数据结构中预先陈述我的假设。
my %allowable_hours = (
m => 500, # I'm assuming that's your other gender :-)
f => 600,
);
unless (exists $allowable_hours{$gender}) {
die "$gender is an unknown gender\n";
}
if ($hours <= $allowable_hours{$gender}) {
# report
} else {
# error
}
更容易编辑允许的时间和添加新的性别(如果有必要的话)。