Eli Eli - 1 year ago 82
Perl Question

Can I Initialize an Array to a Given Size in Perl?

I have a section in my code where I know I will need an array, and I know exactly how many elements that array will need to have. This section of code will be repeated a lot, so I'd could get some very big time savings by first initializing that array to the size I know it will need and then filling it up vs just pushing items on (pushing would be O(n) as opposed to filling up already created spaces, which would be O(1)).

That said, I can't seem to find any elegant way of initializing an array to a given size, and I have no idea why. I know I can do:

my @array; $array[49] =0;

to get a 50 item array, but that looks really ugly to me and I feel as though there must be a better way. Ideas?

Answer Source

To be honest your way is perfectly fine, as is explicitly changing the size of the array: $#array = 49;;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download