That's an odd way to get subsets of three elements. You can't grab them three at a time and maybe the end one has fewer than three elements? As in the example in the docs for splice?
sub nary_print {
my $n = shift;
while (my @next_n = splice @_, 0, $n) {
say join q{ -- }, @next_n;
}
}
nary_print(3, qw(a b c d e f g h));
# prints:
# a -- b -- c
# d -- e -- f
# g -- h
The way forward always starts with a minimal test.
| [reply] [d/l] |
That's not what I'm trying to do. My subset can over lap, so if the initial array is (a,b,c,d,e,f,g,h) the for loop should return:
a
a,b
a,b,c
b,c,d
c,d,e
d,e,f
e,f,g
f,g,h
| [reply] |
c:\@Work\Perl>perl -wMstrict -le
"use List::Util qw(max);
;;
my @ra = qw(a b c d e f g h);
;;
my $n = 3;
for my $i (0 .. $#ra) {
my @triplet = @ra[ max(0, $i - $n + 1) .. $i ];
printf q{'%s' }, join '', @triplet;
}
"
'a' 'ab' 'abc' 'bcd' 'cde' 'def' 'efg' 'fgh'
(The call to max() could be replaced with a ?: ternary if necessary.)
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw/ c h e a p s l i d i n g w i n d o w /;
my $elements = @array;
for ( my $offset = 0; $offset < $elements; $offset++ ) {
for my $length ( 1 .. 3 ) {
next if $length != 3 and $offset >= 1;
my @to_splice = @array;
my @spliced = splice @to_splice, $offset, $length;
print "@spliced\n";
}
}
__END__
Output:
$ perl 1141079.pl
c
c h
c h e
h e a
e a p
a p s
p s l
s l i
l i d
i d i
d i n
i n g
n g w
g w i
w i n
i n d
n d o
d o w
o w
w
$
Note that a "sliding window" is a Thing and if you do some research you'll probably find existing tools for implementing it in your program.
The way forward always starts with a minimal test.
| [reply] [d/l] [select] |
That's not what I'm trying to do. My subset can over lap, so if the initial array is (a,b,c,d,e,f,g,h) the for loop should return:
a
a,b
a,b,c
b,c,d
c,d,e
d,e,f
e,f,g
f,g,h
| [reply] |