It's incorrect because $sixth has never been initialized, so will always be undefined at the point you're attempting to assign its value to $a.

Did you mean this instead?

my $sixth; if (defined $a) { $sixth = $a; } else { $sixth = 3; }

That would make more sense. And if it's what you actually intended to type into your question, yes it is correct. The choice of $a as a variable name is terrible though, because it is the same name used in Perl's sort routine, and is exempt from strictures. Choose any name that isn't $a or $b. Even $c would be ok.

So while my rewrite of your code is correct (assuming it was your original intent and you just wrote it wrong for your question), it's not the most Perlish. In Perl we would do something like this:

my $sixth = defined $a ? $a : 3; # or this my $sixth = $a // 3;

Dave


In reply to Re: Is this code correct by davido
in thread Is this code correct by suvendra123

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.