Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: substrings that consist of repeating characters

by kcott (Archbishop)
on Sep 28, 2020 at 02:42 UTC ( [id://11122283]=note: print w/replies, xml ) Need Help??


in reply to substrings that consist of repeating characters

TMTOWTDI

Given biological data can be huge, using Perl's builtin string-handling functions can often be far more efficient than using regexes. Using Benchmark can help when choosing a solution.

The following code still uses regexes but only minimally:

#!/usr/bin/env perl use 5.014; use warnings; my $string = 'AAATTTAGTTCTTAAGGCTGACATCGGTTTACGTCAGCGTTACCCCCCAAGTTATT +GGGGACTTT'; my $min_repeat = 2; for my $base (qw{A C G T}) { say "$base: ", get_longest_length($string, $base, $min_repeat); } sub get_longest_length { my ($str, $base, $min) = @_; my $re = '[' . 'ACGT' =~ s/$base//r . ']+'; return ( sort { length $b <=> length $a } grep length $_ >= $min, split /$re/, $str )[0]; }

Output:

A: AAA C: CCCCCC G: GGGG T: TTT

Notes:

  • I've specified v5.14 to use the 'r' modifier. See "perl5140delta: Non-destructive substitution".
  • You can use index to find the number and position(s) of maximum-length substring(s).
  • There are a number of optimisations that could be applied, but that will largely depend on your intended usage of this code.

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11122283]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-16 13:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found