in reply to a clearer query for how do i splice an array
in thread how to splice an array?
What task are you trying to accomplish? Are you simply trying to count the occurences of runs of P H A G E? Do the occurances have to happens at particular points in the string (for instance, starting at a position that is a multiple of 5)?
If you have a string (or can make it a string), you can use index to find them and count them. Remember that index returns -1 when it doesn't find the substring, and that's a true value.
#!/usr/bin/perl use strict; use warnings; my $string = "PHAGEPHAGEPQKREPHAGEPWSQEPHAGEPRDLEPHAGE"; my $substring = "PHAGE"; my $count = 0; my $last_pos = -1; NAKED: { $last_pos = index( $string, $substring, $last_pos + 1 ); last if $last_pos == -1; print "Found $substring at $last_pos\n"; $count++; redo; } print "Found $count instances of $substring\n"; __OUTPUT__ Found PHAGE at 0 Found PHAGE at 5 Found PHAGE at 15 Found PHAGE at 25 Found PHAGE at 35 Found 5 instances of PHAGE
If you have an array and you need to find the occurences among consecutive array entries (perhaps, because the array is huge and you want to avoid a lot of copying), you can do the same sort of thing, although you have to invent your own code to find the indices. Scoot along the array and try the subarray at each position. Once it fails, move the starting position (that's $offset) and try again. Do that until you run out of array.
#!/usr/bin/perl use strict; use warnings; my @array = split //, "PHAGEPHAGEPQKREPHAGEPWSQEPHAGEPRDLEPHAGE"; my @subarray = split //, "PHAGE"; my $offset = 0; my $count = 0; NAKED: { foreach my $index ( 0 .. $#subarray ) { next if $array[ $offset + $index ] eq $subarray[ $index ]; $offset += 1; redo NAKED; } print "Found @subarray at $offset\n"; $count++; $offset += @subarray; last if $offset + @subarray > @array; redo; } print "Found $count instances of @subarray\n"; __OUTPUT__ Found P H A G E at 0 Found P H A G E at 5 Found P H A G E at 15 Found P H A G E at 25 Found P H A G E at 35 Found 5 instances of P H A G E
|
|---|