Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 638
Eli Avatar asked Jan 20 '11 19:01

Eli


People also ask

How do you initialize an array of a certain size?

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

How do I assign an array to a variable in Perl?

Perl also enables you to take the current value of an array variable and assign its components to a group of scalar variables. For example: @array = (5, 7); ($var1, $var2) = @array; Here, the first element of the list currently stored in @array, 5, is assigned to $var1.

How do I determine the size of an array in Perl?

Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e. And you can find the maximum index of array by using $#array. So @array and scalar @array is always used to find the size of an array.


2 Answers

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

like image 165
DVK Avatar answered Oct 05 '22 12:10

DVK


  1. The first rule of Optimization Club is, you do not Optimize.
  2. The second rule of Optimization Club is, you do not Optimize without measuring.

Measure, measure, measure before you go and assume that you can do it faster by faking out Perl. Perl's been doing the optimization of common usage a lot longer than you have. Trust it.

like image 30
Andy Lester Avatar answered Oct 05 '22 14:10

Andy Lester