in reply to array pre-allocation trick

Thank you for your ideas. I realize that I could keep the variable in an outer scope, but what I was trying to do was preallocate space without having it filled up with undefs, so I could use push on the array. My example code should have included a loop like the following inside the subroutine after the "Push stuff on the array here" comment:
for (1..5000) { push @array,$_; }

Replies are listed 'Best First'.
Re: Re: array pre-allocation trick
by rir (Vicar) on Oct 31, 2002 at 04:41 UTC
    I apologize, I didn't read that comment strictly enough.

    No, push is going to grow your array. Try something like:

    for ( 0..4999) { $array[$_] = $_; }
    Although if you really are really tight, you may want to test if a while or C-style loop is faster than building the list of integers.
Re^2: array pre-allocation trick
by Aristotle (Chancellor) on Oct 31, 2002 at 19:22 UTC
    Sounds like you want to have a look at the map function, actually. my @array = map { do_stuff_with($_); $_ } 1 .. 5000;

    Makeshifts last the longest.