initialize a list

  • Thread starter gnu valued customer
  • Start date
G

gnu valued customer

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
 
J

Jay Tilton

: 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);
 
A

Ala Qumsieh

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

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

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

--Ala
 
U

Uri Guttman

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
 
B

Brian McCauley

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

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?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,891
Members
47,423
Latest member
henerygril

Latest Threads

Top