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

Me again. lol. I know with perl you don't have to state the size of an array at the beginning as it grows as required, but is there a way of dictating how large you want the array from the beginning? Thanks very much.

Replies are listed 'Best First'.
Re: size of array
by tlm (Prior) on May 04, 2005 at 12:58 UTC

    You can pre-grow the array by assigning to the variable corresponding to its last index:

    $#arabian_nights = 1000;
    This will tell perl that you want an array @arabian_nights of size 1001, but it won't prevent perl from adding elements past the pre-grown size. You can always truncate the array to the size you want, also by assigning to its last-index variable. (In other words, the line above sets the size of the array; whether this amounts to "pre-growing" or "truncating" depends on the size of the array at the time.)

    BTW, you can "pre-grow" a hash too, by assigning to keys:

    keys %mongo = 1_000_000;
    Pre-growing, both for arrays and hashes, makes perl more efficient, since it doesn't need to jump through memory reallocation hoops every time the array or hash grows past the space allocated to it by default.

    the lowliest monk

Re: size of array
by Fletch (Bishop) on May 04, 2005 at 13:02 UTC
Re: size of array
by reasonablekeith (Deacon) on May 04, 2005 at 13:20 UTC
    I think the general sentiment here is...

    Write clear, easily maintainable code. If, when you've finished your program, you find that it runs too slowly you can then easily do stuff like this to go back and make it run a bit faster.

Re: size of array
by Grygonos (Chaplain) on May 04, 2005 at 13:01 UTC

    I don't think you're going to gain any efficiency or clarity from declaring it as such. I would just make a comment when you declare the array

    #@large will hold a 1000 element list my @large;
    rather than
    #@large will hold a 1000 element list my @large; $#large = 1000;

Re: size of array
by Angharad (Pilgrim) on May 04, 2005 at 13:21 UTC
    Thanks everyone. :)
Re: size of array
by sh1tn (Priest) on May 04, 2005 at 13:02 UTC
    # define $#array @a = 1..5; print scalar @a, "\n"; $#a++ for 1..5; print scalar @a, "\n";


      sh1tn, $#a++ for 1..5; is basically the same as
      for (1..5) { $#a=$_; }
      what makes no sense in my eyes. Why assigning 1..4 when you end up with 5 and do nothing in between?

      Anyway, here's mine:
      my @a = (0) x 5


      holli, /regexed monk/
        Yes, you are right holli.
        I ment to show what happens with each iteration.
        Everyone has the right to dislike my style.