while (@lines) { $output .= ""; for ( 1 .. 3 ) { $output .= "" . (shift @lines) . ""; } $output .= ""; } #### my $fill = scalar @lines % 3; while ($fill-- > 0) { push @lines, " "; }