How do I initialize an array to 0?
I have tried this.
my @arr = ();
But it always throws me a warning, "Use of uninitialized value". I do not know the size of the array beforehand. I fill it dynamically. I thought the above piece of code was supposed to initialize it to 0.
How do I do this?
To empty an array in Perl, simply define the array to be equal to an empty array: # Here's an array containing stuff. my @stuff = ("one", "two", "three"); @stuff = (); # Now it's an empty array!
If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:
use strict; use warnings; my @other_array = (0,0,0,1,2,2,3,3,3,4); my %tallies; $tallies{$_} ++ for @other_array; print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;
Output:
0 => 3 1 => 1 2 => 2 3 => 3 4 => 1
To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:
my @zeroes = (0) x 5; # (0,0,0,0,0) my @zeroes = (0) x @other_array; # A zero for each item in @other_array. # This works because in scalar context # an array evaluates to its size.
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With