Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: Hash Manipulation

by hippo (Bishop)
on Jun 08, 2021 at 15:19 UTC ( [id://11133664]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Hash Manipulation
in thread Hash Manipulation

In your code you have this block (I've shortened the print statements for clarity):

if ($ele eq 0){ } else { if ($ele eq 1){ print "Condition: ele is 1\n"; } else { print "Condition: ele is neither 1 nor 0\n"; } }

This is confusing because of the empty block straddling the first 2 lines. There are a couple of ways to avoid it in general. One is to negate the condition:

if ($ele ne 0){ if ($ele eq 1){ print "Condition: ele is 1\n"; } else { print "Condition: ele is neither 1 nor 0\n"; } }

The other is to turn the if into an unless:

unless ($ele eq 0){ if ($ele eq 1){ print "Condition: ele is 1\n"; } else { print "Condition: ele is neither 1 nor 0\n"; } }

Either of these removes the empty block, so that's a plus. But we can go farther. The logic can be simplified because really you have only 2 conditions as indicated by my rewritten print statements. So we can remove the outer condition by folding it into the else like so:

if ($ele eq 1){ print "Condition: ele is 1\n"; } elsif ($ele ne 0) { print "Condition: ele is neither 1 nor 0\n"; }

Finally, deducing from your previous code that $ele is only ever a whole number you can switch to using numerical comparisons rather than string comparisons (== instead of eq, etc.). Perhaps this is the clearest:

if ($ele == 1) { print "Condition: ele is 1\n"; } elsif ($ele > 1) { print "Condition: ele is neither 1 nor 0\n"; }

I understand that you are just hacking about with this code but wanted to point out these alternative ways of going about the logical if-blocks. The simpler you can make it the fewer bugs can creep in and that has to be a good thing.


🦛

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11133664]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-03-28 17:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found