8

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?

1
  • It is always good to maintain use strict and use warnings Commented Jan 20, 2016 at 6:59

2 Answers 2

17

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

Comments

7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.