Martha Elena Ibarra Martha Elena Ibarra - 7 months ago 16
Perl Question

getting every possible substring in perl

I would like to generate every possible consecutive substring of a string, including the end of the word/beginning from the word (cyclic) letter combinations. I've found an example in Python, but the only language I know is perl (and barely, I'm a beginner). I would appreciate it a lot if someone can help me translating the code to perl or to help me find a solution in perl.

the code is the following:

aa='ABCD'

F=[]

B=[]

for j in range(1,len(aa)+1,1):

for i in range(0,len(aa),1):

A=str.split(((aa*j)[i:i+j]))

B=B+A

C=(B[0:len(aa)*len(aa)-len(aa)+1])


it gives you:

C=['A', 'B', 'C', 'D', 'AB', 'BC', 'CD', 'DA', 'ABC', 'BCD', 'CDA', 'DAB', 'ABCD']`

Answer
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $string = 'ABCD';

my @substrings;
for my $length (1 .. length $string) {
    for my $pos (0 .. length($string) - 1) {
        push @substrings, substr $string x 2, $pos, $length;
    }
}

say for @substrings;
Comments