Your problem reminds of this old node: Rosetta code: Split an array into chunks
Adapting that code to your problem shows how we can employ functions
from List::MoreUtils to this problem.
use strict;
use warnings;
use List::MoreUtils qw(part natatime);
use Data::Dumper;
# Load test DATA below into an array of teams (adapted from original n
+ode)
my $line;
my @teams;
while ( $line = <DATA> ) {
chomp $line;
if ($line =~ /^#/ || $line =~ /^\s*$/) {
next;
}
$line =~ s/^[^=]*\=//;
push @teams, split( /,/, $line );
}
print Dumper \@teams;
# ------------------------------------------------------
# Adapted from https://perlmonks.org/?node_id=861938
# Using natatime
sub chunk_array {
my ($n, @vals) = @_;
my $str;
my $iter = natatime($n, @vals);
while ( my @line = $iter->() ) {
$str .= join(",", @line) . ",\n";
}
$str =~ s/,$//;
return $str;
}
# Using part
sub chunk_array_2 {
my ($n, @vals) = @_;
my $str;
my $i = 0;
$str = join "", map { join(",", @$_).",\n" } part { $i++/$n } @val
+s;
$str =~ s/,$//;
return $str;
}
my $v1 = chunk_array(3, @teams);
print "Version 1--------------\n";
print $v1;
my $v2 = chunk_array_2(3, @teams);
print "Version 2--------------\n";
print $v2;
#---------------------------------------
__DATA__
Teams=PATRIOTS,BILLS,DOLPHINS,JETS,COWBOYS,GIANTS,EAGLES,REDSKINS,BENG
+ALS,OILERS,STEELERS,BROWNS,SEAHAWKS,RAMS,49ERS,RAIDERS
Running the test program above produces:
$VAR1 = [
'PATRIOTS',
'BILLS',
'DOLPHINS',
'JETS',
'COWBOYS',
'GIANTS',
'EAGLES',
'REDSKINS',
'BENGALS',
'OILERS',
'STEELERS',
'BROWNS',
'SEAHAWKS',
'RAMS',
'49ERS',
'RAIDERS'
];
Version 1--------------
PATRIOTS,BILLS,DOLPHINS,
JETS,COWBOYS,GIANTS,
EAGLES,REDSKINS,BENGALS,
OILERS,STEELERS,BROWNS,
SEAHAWKS,RAMS,49ERS,
RAIDERS
Version 2--------------
PATRIOTS,BILLS,DOLPHINS,
JETS,COWBOYS,GIANTS,
EAGLES,REDSKINS,BENGALS,
OILERS,STEELERS,BROWNS,
SEAHAWKS,RAMS,49ERS,
RAIDERS
References Added Later