Sometimes, for the sake of readability1, assigning '' to a variable is better that leaving it undefined, or assigning undef.

That said, it is possible for assigning '' to a variable hides errors that might otherwise be detected by the warning.

As long as the coder is aware of the trade-offs, the coder can choose the alternative that best fits a given situation.

---

1 Just adding a comment explaining what you are doing and why can actually confuse the reader:

my $buf; # leave value as undefined so use before a real value is avai +lable will result in a warning message. ...; while (<$input>) { ...; $buf .= $newletter; # not an error because appending to an undef v +alue is treated the same as appending to an empty string }

While the above is certainly valid Perl code (and doesn't produce a warning), there are a lot of code reviewers who will reject this, citing it as being confusing.

And, often, the same reviewers will reject:

if (defined $buf) { $buf .= $newletter; } else { $buf = $newletter; }

as being too complex.

But:

my $buf = ''; ...; while (<$input>) { ...; $buf .= $newletter; }

is clear about what is being done and comfortable to the reviewers.

Sometimes debugging a weird bug is easier than arguing with the reviewers.


In reply to Re^2: declare and init a scalar by RonW
in thread declare and init a scalar by fionbarr

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.