| Refresh | Home EGTry.com

split list into sublist


use strict;
use POSIX;

my @List=(1 .. 10);
my $chunk_size=3;

my $chunks=listSplit(\@List, $chunk_size);

foreach my $chunk (@$chunks) {
  print join(",", @$chunk), "\n";
}

sub listSplit {
  my ($list, $chunk_size)=@_;
  my @sublists;

  my @list=@$list;
  my $size=@list;
  my $n=$size/$chunk_size;
  $n=ceil($n);

  for(my $i=0; $i<$n-1; $i++) {
    my @sublist=@list[$i*$chunk_size .. ($i+1)*$chunk_size-1];
    push @sublists, \@sublist;
  }

  #different treatment of the last chunk
  my @sublast;
  my $from=($n-1)*$chunk_size;
  my $to=$size-1;
  if ($from==$to) {
    @sublast=($list[$from]);
  } else {
    @sublast=@list[$from .. $to];
  }
  push @sublists, \@sublast;

  return \@sublists;
}



Output

1,2,3
4,5,6
7,8,9
10