in reply to Re^4: Sub-setting an Array
in thread Sub-setting an Array

Like this?

#!/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.

Replies are listed 'Best First'.
Re^6: Sub-setting an Array
by Anonymous Monk on Sep 05, 2015 at 01:17 UTC
    Interesting, I have never heard of "sliding windows" before. I do not want the final windows to have less than 3 elements so, if I look at your output, the code would have to stop after "d o w".

      Well, how would you say that in English?

      Something like "Stop if the difference between the position of the element we're on and the length of the array is smaller than the length of the window we want", right? So in Perl that might be as simple as:

      last if $elements - $offset < 3;
      Which will stop the whole loop as soon as it's true. Add it after the next statement and see what happens.

      Edit: If you are really wanting to get a sliding subset of the array, you wouldn't want to use splice since as you can see it changes the original array and soon you have no elements left! But making a copy of the array each time through a loop, as I did in the example, is horribly inefficient, and the example is only designed to explain the use of splice, which is what the OP asked for ...

      The way forward always starts with a minimal test.
        Makes perfect sense! Thanks for your feedback.

        Interesting, I have never heard of "sliding windows" before.... Well, how would you say that in English?

        Great question

        Maybe a FIFO/Queue of size N?

        Hmm, there is a Sliding window protocol, haha