http://www.perlmonks.org?node_id=47523

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Simple question:
I need to initialize 20 variables($var1..$var20) to zero.
$var1=0; $var2=0; $var3=0; ...

How do I do this with arrays in Perl?

Thanks...Mike

  • Comment on How can I create an array that holds number of variables with values?
  • Download Code

Replies are listed 'Best First'.
Re: How can I create an array that holds number of variables with values?
by runrig (Abbot) on Dec 20, 2000 at 06:13 UTC
    my @array = map {0} 0..19;
      my @array = (0)x20;
Re: How can I create an array that holds number of variables with values?
by Russ (Deacon) on Dec 27, 2000 at 03:36 UTC
    Your question almost answers itself
    my @var = (43, 60, 1..18); # Later... print $var[1], $var[14];
    Use an array instead of multiple, distinct variables.

    turnstep is right, you don't have to initialize all the variables to zero, just create them where you need them, giving a value at that time.

    runrig's code (my @array = map {0} 0..19) works fine here, as well.

Re: How can I create an array that holds number of variables with values?
by turnstep (Parson) on Dec 26, 2000 at 08:22 UTC
    Also keep in mind that you may not need to initialize them at all - perl can usually figure out what you want to do. For example
    my $var1; $var1++; print "Var1 is now $var1\n"; my $var2; $var2 = "Foobar"; print "Var2 is now $var2\n";
    Both of the above will work fine. The values start out undefined, and in most cases (but not all) they do not need an explicit initialization.

Re: How can I create an array that holds number of variables with values?
by I0 (Priest) on Dec 20, 2000 at 09:13 UTC
    ${"var$_"}=0 for(1..20); #but why aren't you using @var[1..20] ?

    Originally posted as a Categorized Answer.

Re: How can I create an array that holds number of variables with values?
by runrig (Abbot) on Dec 20, 2000 at 06:15 UTC
    Or do you mean:
    my @array = \my ($var1, $var2, $var3); $$_ = 0 for @array;

    Originally posted as a Categorized Answer.

Re: How can I create an array that holds number of variables with values?
by Anonymous Monk on Dec 20, 2000 at 06:45 UTC
    let me put it in that way: I want to use these variables later in my program rather initializing like this: $var1=0; $var2=0; $var3=0; How can I define an array, so that I can use these variables to assign them later something else ? (i.e: $var1= 43; $var2 = 60; etc...

    Originally posted as a Categorized Answer.