why the unless function in perl isn't working

145 Views Asked by At

I was writing a simple perl script which calculates payment based on the hours given by the user and the program mustn't allow payments above 500 hrs but has to allow upto 600 for females, and I was using the unless function but it is not working it allows more than 600 hrs for females.

here is the code I used

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!");
        }
    }
2

There are 2 best solutions below

1
Quentin On BEST ANSWER

Break it down.

it allows more than 600 hrs for females.

Let's try some test data.

$gender = "f";
$hours = 750;

Feed that into your test:

unless($gender ne "f" && $hours>=600){

Replace the variables with the values

unless("f" ne "f" && 750>=600){

Convert the tests to booleans

unless(false && true){

Resolve the logical operator

unless(false);

Which means it runs the expression.


You're confusing yourself with a double negative.

Try to simplify the logic by splitting it apart and avoiding negatives.

my $allowedHours = 500;
if ($gender eq "f") {
    $allowedHours = 600;
}
if ($hours <= $allowedHours) {
    # report
} else {
    # error
}
0
Dave Cross On

I always like to state my assumptions up front in a data structure.

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
}

Makes it easier to edit the allowable hours and add new genders (if that ever becomes necessary).