while ($count < $elements) { # Do you use $tr? If not, then don't bother declaring it... foreach my $tr (1..$cols) { $test .= ""; foreach my $tc (1..$rows) { $count++; # Do stuff } } }