Perl automatically initializes variables to undef
by default.
Is there a way to override this default behavior and tell the Perl interpreter to initialize variables to zero
(or some other fixed value)?
Creating Variables The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Keep a note that this is mandatory to declare a variable before we use it if we use use strict statement in our program.
A scalar variable, or scalar field, is a variable that holds one value at a time. It is a single component that assumes a range of number or string values.
@ is used for an array. In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function: sub Average{ # Get total number of arguments passed. $ n = scalar(@_); $sum = 0; foreach $item (@_){ # foreach is like for loop...
A scalar variable can store either a number, a string, or a reference and will precede by a dollar sign ($). An array variable will store ordered lists of scalars and precede by @ sign. The Hash variable will be used to store sets of key/value pairs and will precede by sign %.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With