notagoodcoder
notagoodcoder

Reputation: 11

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.

Upvotes: 1

Views: 99

Answers (2)

David W.
David W.

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

cjm
cjm

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

Related Questions