Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading