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.
🦛
In reply to Re^3: Hash Manipulation
by hippo
in thread Hash Manipulation
by JusaEngineer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |