Reputation: 11
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.
Upvotes: 1
Views: 99
Reputation: 107090
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.
Upvotes: -1
Reputation: 62109
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";
}
Upvotes: 2