Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to an array in Perl

Tags:

arrays

perl

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?

like image 964
Scra Avatar asked Jun 06 '26 03:06

Scra


1 Answers

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;
like image 164
Matt Jacob Avatar answered Jun 09 '26 02:06

Matt Jacob