in reply to Re: declare and init a scalar
in thread declare and init a scalar

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.

Replies are listed 'Best First'.
Re^3: declare and init a scalar
by BrowserUk (Patriarch) on Jan 23, 2015 at 00:11 UTC
    Sometimes debugging a weird bug is easier than arguing with the reviewers.

    I agree! But...debugging is about finding errors; if you arbitrarily disable the diagnostics that will tell where the error originates you make life much harder.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      Not so much as disabling a diagnostic as "circumventing" it.

      On the other hand, if the coder knowingly initializes a variable that could better be left undefined, she/he can make note of it, preferably in the code and in a way that doesn't panic the code reviewers.