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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.