Reputation: 137
I have this code where I want to add 10, 11 and 12 to array arr.
my @num=(0,1,2);
my $i=10;
for my $d (@num){
if (defined($d)) {
my @arr;
$arr[$d] = $i;
$i=$i+1;
my $dvv=dump(\@arr);
print "**** $dvv \n";
}
}
The output is:
**** [10]
**** [undef, 11]
**** [undef, undef, 12]
Why is only the last element of array defined?
Upvotes: 7
Views: 39999
Reputation: 6437
Since you have the declaration of the array within the loop, it will re-create it each time, removing any values that would have been placed in it on previous iterations of the loop.
You should declaure @arr
before the loop if you want the values to stay:
my @arr;
for my $d (@num) {
...
}
And because of this line:
$arr[$d];
$d
is the position defined by the other array (0, then 1, then 2). So it puts the value of $i
in that position in the array, and puts values before to undef
.
Upvotes: 7
Reputation: 6553
AntonH's answer addresses the specific problem with your specific code, but there are actually ways to rewrite your code that would avoid the problem entirely. A more "Perlish" way to accomplish the same thing would be:
my @arr;
for my $i (0 .. 2) {
push(@arr, $i + 10);
}
Or:
my @arr = map { $_ + 10 } 0 .. 2;
Or just:
my @arr = 10 .. 12;
Upvotes: 16