perlunless

why the unless function in perl isn't working


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

Solution

  • 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
    }