How can I automatically initialize all the scalar variables in Perl?

The recommendation in Code Complete is important for language such as C because when you have

int f(void) {
   int counter;
}

the value of counter is whatever happens to occupy that memory.

In Perl, when you declare a variable using

my $counter;

there is no doubt that the value of $counter is undef not some random garbage.

Therefore, the motivation behind the recommendation, i.e. to ensure that all variables start out with known values, is automatically satisfied in Perl and it is not necessary to do anything.

What you do with counters is to increment or decrement them. The result of:

my $counter;
# ...
++ $counter;

is well defined in Perl. $counter will hold the value 1.

Finally, I would argue that, in most cases, counters are not necessary in Perl and code making extensive use of counter variables may need to be rewritten.


As far as I know, this is not possible (and shouldn't be, its even more dangerous than $[).

You can initialize your variables as follows to cut down on boilerplate:

my ($x, $y, $z) = (0) x 3;

or move initialization to a function:

sub zero {$_ = 0 for @_}

zero my ($x, $y, $z);

or even:

$_ = 0 for my ($x, $y, $z);

No. Doing this can lead to some very scary and hard-to-decipher bugs, so it's not a good idea to change behaviour like this anyway.

In Perl, you can declare variables right when you need them for the first time, so there isn't generally a need to declare them first (with or without initialization) and then using them later. Additionally, operators such as ++ will work with undefined values equally well as zero, so you don't need to initialize counters at all:

# this is perfectly legal:
my $counter;
while ($some_loop)
{
    $counter++;
}

However, I can insert a plug for Moose by mentioning that you can achieve automatic initialization of attributes in your Moose classes:

package MyClass;
use strict;
use warnings;
use Moose;

has some_string => (
    is => 'rw', isa => 'Str',
    default => 'initial value',
);

has some_number => (
    is => 'rw', isa => 'Int',
    default => 0,
);
__PACKAGE__->meta->make_immutable;
1;

package main;
my $object = MyClass->new;
print "string has value: ", $object->some_string, "\n";
print "number has value: ", $object->some_number, "\n";

prints:

string has value: initial value
number has value: 0