jnmf jnmf - 7 months ago 9
Perl Question

modify this code to print elements that differ a x number from previous position

I wrote this code to find substrings every x elements:

print "enter file path\n";
$letters = <>;
chomp ($letters);

$sequence = "";

open (LETTERS, $letters) or die "error opening\n";

print "how many letters at a shot\n";
$number = <>;
chomp ($number);

$size = length $sequence;
chomp ($size);


for ($i = 0; $i < $size; $i++) {
$test = substr ($sequence, $i, $number);
print "> Test $i\n";
print "$test\n";

if ($i >= $size - $number) {
last;
}

}


so if I open a file with this string and choose x = 3:

abcdefg


I get this result:

> Test 0 abc
> Test 1 bcd
> Test 2 cde
> Test 3 def
> Test 4 efg


Each substring differs from one position from the previous substring, I'd like to be able to control this number and dislocate the substring by 2 for example. So the result would be:

> Test 0 abc
> Test 2 cde
> Test 4 efg


Any suggestions? Thanks

Answer

Add:

...
$step = <>;
...

And change:

for ($i = 0; $i < $size; $i++) {

to

for ($i = 0; $i < $size; $i+=$step) {
Comments