use strict; use warnings; use Data::Dumper; my @array = qw(a b c e 1 2 3 4 5 3 f); my $len = 3; my @stack = map{$_%$len?():[grep{$_}@array[$_..$_+$len-1]]} 0..@array-1; print Dumper \@stack;