You are using the wrong or there. It will work often, except where it causes hard to find bugs. Instead, use || for "OR" expressions. Use or for control of flow, and || for expressions that evaluate to a value, as a general rule of thumb. The issue is the low precedence of or, which will trick you sometimes.

So the first code snippet above could be written as:

$var = $var || 30; # or $var ||= 30; # or $var = $var ? $var : 30; # or if you care about definedness rather than Boolean truth: $var = $var // 30; # or #var //= 30; # or $var = defined($var) ? $var : 30;

Your second code snippet is also probably broken, because undef $var will set $var to undef and will then evaluate the expression's value, which is now always going to be undef. You probably meant this:

if (! defined $var) { $x = 40; } else { $x = 50; }

Which might be written more elegantly like this:

$x = defined $var ? 50 : 40;

For what it's worth, some of this applies equally in many languages such as C and C++. There's not really a concept of definedness in C/C++, but the concept of short circuiting in expressions using ||, and of ternary operators is nearly identical.


Dave


In reply to Re: Need clean code by davido
in thread Need clean code by ravi45722

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.