To get all possible K length substrings of a string in Perl, you can use nested loops to iterate through each possible substring.
In this example,
$str
with a value of "Hello World"
.@substrings
to store all substrings of length 3.substr
function and add it to the @substrings
array.@substrings
array.$str = 'Hello World';
$k = 3;
@substrings = ();
for ($i = 0; $i <= length($str) - $k; $i++) {
for ($j = $i; $j < $i + $k; $j++) {
push(@substrings, substr($str, $i, $k));
}
}
print "All substrings of length $k: @substrings\n";
All substrings of length 3: Hel ell llo loo o W Wo Wor orl rld
In this tutorial, we learned How to get all the possible K length Substrings in a String in Perl language with well detailed examples.