Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postfix for loop in perl is not working as expected

Tags:

syntax

perl

The following line works perfectly

for(my $i=0; $i < ($max_size - $curr_size) ; $i++){
    push (@{$_}, 0);
}

But this one doesn't.

push (@{$_}, 0) for (1 .. ($max_size - $curr_size));

It gives me an error message like this:

Can't use string ("1") as an ARRAY ref while "strict refs" in use at coordReadEasy.pl line 124, <DATA> line 16.

Why? how can I solve this?

like image 736
Alby Avatar asked Aug 25 '13 02:08

Alby


1 Answers

The range version of for sets $_ to each element, so in @{$_} you’re trying to dereference $_ as though it were an array reference. These are all equivalent:

for my $x (1..10) {
  print "$x\n"
}

for (1..10) {
  print "$_\n"
}

print "$_\n" for (1..10);

The easy solution is to create another variable for your array reference:

push @{$ref}, 0 for 1 .. $max_size - $curr_size;
like image 161
Jon Purdy Avatar answered Nov 03 '22 17:11

Jon Purdy