my $rect_width = 10; my $rect_height = 10; for my $i (0 .. ($width - 1)/ $rect_width) { my $x_left = $i * $rect_width; my $x_right = $x_left + $rect_width - 1; $x_right = $width - 1 if $x_left >= $width; for my $j (0 .. ($height - 1) / $rect_height) { my $y_top = $j * $rect_height; my $y_bottom = $y_top + $rect_height - 1; $y_bottom = $height - 1 if $y_bottom >= $height; $im->filledRectangle($x_left,$y_top,$x_right,$y_bottom,$colors[int(rand($total))]); } }