Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 259
Lazer Avatar asked Nov 03 '10 18:11

Lazer


People also ask

How do I initialize a variable in Perl?

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.

How many variables can a scalar variable hold at one time?

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.

What does @_ mean in Perl?

@ 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...

How will you define a scalar variable and an array in Perl?

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 %.


2 Answers

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.

like image 151
Sinan Ünür Avatar answered Sep 28 '22 17:09

Sinan Ünür


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);
like image 21
Eric Strom Avatar answered Sep 28 '22 16:09

Eric Strom