35

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?

6
  • 5
    Show us the code you're having trouble with. Why do you need it set to 0? XY problem Commented Jul 15, 2010 at 0:06
  • It is something similar to this. I have another array with numbers like [0,0,0,1,2,2,3,3,3,4] now I have to count the number of 0,1,2,3,4 so I will use another array...and store the count in given index. so I will have arr[0] = 3 arr[1] = 1 arr[2] = 2 arr[3] = 3 arr[4] = 4 so as and when I encounter an element I do... arr[i] = arr[i] + 1; for this I need to start with elements initilized with 0. The above code works. But it also throws a warning. Commented Jul 15, 2010 at 0:49
  • 1
    You can do $arr[i]++ instead of $arr[i] = $arr[i] + 1; also if your array is empty, $arr[i]++ will still set $arr[i] to 1; Commented Jul 15, 2010 at 1:27
  • @MkV $arr[i] += 1; can be better in some cases, ++ has some magic in Perl that causes it to be a bit slower. Commented Jul 15, 2010 at 21:59
  • 1
    @Ven'Tatsu: do you have a cite for that (the slowdown)? I know there is magic when it is undef (pre-converted to 0) or a string. I am not seeing significant (>1 microsecond) differences in speed when benchmarking. Commented Jul 16, 2010 at 3:33

3 Answers 3

67

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Thats amazing. But still wonder, why cant I have array elements initialsed to 0. without using hash. The problem is it just works, but gives me a warning before accessing an uninitialsed value.
@jerrygo: are you by any chance using an old version of perl? This code above should not give you any warnings.
@Ether: Strange. I use strawberry perl version 5.16 and I still get the warning message. To avoid this I insert a condition: if (def $value) { push(@array,$value) } else { push(@array,"") }.
26

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.)

8 Comments

Sorry. Yes. I want to initialise the elements of the array to 0.So that I can use the array as some sort of counter for each index. Please refer above comment for exact problem.
if you want to initialise an array to having the same number of elements as another array all of a specific value; do something like; my @arr2 = (0) x @arr1;
@MkV: or my @arr2=(0) x $#arr1 as well, no?
@jerrygo: you don't need to explicitly initialize the array to all zeroes; if you do $array[$i]++ from an empty array, things will "just work".
@drewk: no, $#arr1 is not the same as scalar(@arr1). For an array with five elements, the former is 4 and the latter is 5 (assuming you haven't altered $[ from its default).
|
5

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.