in reply to Auto-filling an array

And then there's

my @list; push(@list, 'N/A') for (1..14);

Perl's push, pop, shift and unshift are extremely efficient. They don't copy the entire array, unlike @list=('N/A')x14. In addition, for (a..b) is also very efficient. It is optimised to not create a list, unlike ('N/A')x14.

That said, I like the idea of leaving the array undefined, and replacing each undef with "N/A" when printing.

Replies are listed 'Best First'.
Re^2: Auto-filling an array
by tlm (Prior) on Mar 28, 2005 at 23:39 UTC

    I was very intrigued by ikegami's post, so I went ahead and benchmarked the two approaches:

    use Benchmark 'cmpthese'; cmpthese( -1, { x => sub { my @list = ( 'N/A' ) x 14 }, push => sub { my @list; push @list, $_ for 1 .. 14 } } ); Rate times push x 89321/s -- -23% push 115925/s 30% --
    Where would I be without Benchmark?

    the lowliest monk

Re^2: Auto-filling an array
by nimdokk (Vicar) on Mar 28, 2005 at 19:13 UTC
    I actually tried putting the 'N/A's in when I was writing the list, but the data was not coming back right, so I went with a more brute force approach. That said of course. I'm going to be looking at other ways to tighten this script up.