PBP: 054 Initialization

Mr. Conway suggests that you initialize any variable you localize.

The reasons given for this are clear and useful.  Not doing so means you may have a different value in the variable than you expect.  You’re localizing it to use it, so do so.  Specifying a value when you localize it – even if you change it later – adds clarity at very little cost.

I often go further.  My background is old C code.  I tend to initialize every variable, even if Perl’s default would have been fine.  Some people complain about this, but I think it adds as much value as the suggestion here; the value I expect this to start with is explicitly stated, instead of understood to be something.  It also lets me avoid many “undef” warnings, because I’ll initialize the variable to zero or the empty string instead of leaving it float as undef.

2 Responses to “PBP: 054 Initialization”

  1. Chas. Owens says:

    The downside to that (setting all variables vs just localized ones) is you can’t tell if the variable was set to a meaningful value or not. Setting scalars to 0 or “” when that is not the expected value is just as bad as undef. In fact, it is worse since it is functionally the same as undef, but won’t produce a warning message. I do agree that variables should be set when they are declared, but only if you have a meaningful value to set them to.

  2. Ed Avis says:

    I don’t believe this is the reason. In fact, ‘local’ sets the value to undef:

    our $a = 1;
    { local $a; say $a // ‘undef’ }

    will print ‘undef’. The reason to have an explicit initializer is just because everyone forgets that ‘local’ does this, so you might unintentionally write code that localizes a variable expecting to keep the same value. If you want that, you need to do it explicitly:

    local $a = $a;

    There is some discussion on the Perl::Critic bug tracker about how far this advice should apply to builtin variables such as $! which are sometimes localized but assigning to them may not make much sense. https://github.com/Perl-Critic/Perl-Critic/issues/314

Leave a Reply to Chas. Owens