$i = 0; $open = 0; foreach (@images) # or: while ($sth->fetch) # or: while (readdir(IMAGE_DIR)) { (print "", $open = 1) unless $open; print ""; # print image print "" (print "", $open = 0) unless ++$i % 5; } print "" if $open;