# initialize a list

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hello,

strings
--------
my (\$a, \$b, \$c, \$d, \$e) = ''; # only \$a is defined

my (\$a, \$b, \$c, \$d, \$e) = ('') x 5; # all 5 are defined

numbers
--------
my (\$a, \$b, \$c, \$d, \$e) = (0) x 5; # works for int too

Is the above use of the repetition operator (x) a
good practice for initializing a List, or are there
better ways?

tia,
tlviewer

## Re: initialize a list

: strings
: --------
: my (\$a, \$b, \$c, \$d, \$e) = ''; # only \$a is defined
:
: my (\$a, \$b, \$c, \$d, \$e) = ('') x 5; # all 5 are defined
:
: numbers
: --------
: my (\$a, \$b, \$c, \$d, \$e) = (0) x 5; # works for int too
:
: Is the above use of the repetition operator (x) a
: good practice for initializing a List,

Do the variables in the list really need to be initialized?  Giving them
values of 0 or '' doesn't do anything Perl can DWIM on its own.

: or are there better ways?

My personal preference in the extraordinarily rare circumstance that
initialization is necessary:

\$_ = 0 for
my (\$a, \$b, \$c, \$d, \$e);

## Re: initialize a list

Jay Tilton wrote:

Hmmm .. I would have expected the variables to be defined only within
the "body" of the for loop. Why does this work?

--Ala

## Re: initialize a list

AQ> Jay Tilton wrote:
>> My personal preference in the extraordinarily rare circumstance that
>> initialization is necessary:
>> \$_ = 0 for
>> my (\$a, \$b, \$c, \$d, \$e);

AQ> Hmmm .. I would have expected the variables to be defined only within
AQ> the "body" of the for loop. Why does this work?

that expression (not really a loop body) isn't a block so there is no
scope. the my is scoped to the enclosing block. this isn't any different
than saying open( my \$fh, 'foo' ).

uri

--
Uri Guttman  ------  uri@stemsystems.com  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org

## Re: initialize a list

gnu valued customer wrote:

Others have shown you a better way, but I would also like to point out
that you may want to take a step back and consider if you are doing the
right thing.

I work by the rule of thumb that says if you are doing it 3 times you
are probably doing it wrong.  If you are initialising 5 separate scalar
values to the same initial value at the same point there's a strong
chance you really wanted some sort of agregate rather than 5 separate
scalars.

Note I said 'probably' and 'strong chance'- it doesn't always hold -
it's just something that you should think about.