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?
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;
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