How can I print an array in chunks with a delimeter as the last character of the line in all but the last line
I have the following:
my @array = qw/a b c d e f g 开发者_运维技巧h i j/;
my $elements_per_line =4;
I need the output to look like this:
a | b | c | d |
e | f | g | h |
i | j
I have tried this:
while (@array) {
print join " | ", splice(@array, 0, $elements_per_line), "\n";
}
But that results in the " | " at the end of all 3 lines.
Here's one way:
my @array = qw/a b c d e f g h i j/;
my $elements_per_line =4;
while (@array) {
print join " | ", splice(@array, 0, $elements_per_line);
print " |" if @array;
print "\n";
}
How about a solution not using join or splice?
my $count = 0;
foreach my $element (@array) {
print "$element | ";
$count++;
if (($count % $elements_per_line) == 0) {
print "\n";
}
}
Don't know if it's as efficient as the split
/join
, but it is easier to understand.
精彩评论