Hi,
I am trying to put the bracket in a string given the set of its substrings. Like this:
String Substrings Desired Result 1.CCCATCTGTCCTTATTTGCTG ATCTG ATTTG CCC[ATCTG]TCCTT[ATTTG]CTG 2.ACCCATCTGTCCTTGGCCAT CCATC AC[CCATC]TGTCCTTGGCCAT 3.CCACCAGCACCTGTC CCACC CCAGC GCACC [CCACCAGCACC]TGTC * 4.CCCAACACCTGCTGCCT CCAAC ACACC C[CCAACACC]TGCTGCCT *
My code here does the job, but only for the first two cases (where the substrings don't overlap in the string). It fails to deal with case 3 and 4 (marked with asterisks *).
#!/usr/bin/perl -w use strict; my $s1 ='CCCATCTGTCCTTATTTGCTG'; my @a1 = qw(ATCTG ATTTG); my $s2 ='ACCCATCTGTCCTTGGCCAT'; my @a2 = qw(CCATC); my $s3 ='CCACCAGCACCTGTC'; my @a3 = qw(CCACC CCAGC GCACC); my $s4 ='CCCAACACCTGCTGCCT'; my @a4 = qw(CCAAC ACACC); #These two work fine. put_bracket($s1,\@a1); put_bracket($s2,\@a2); #But these two don't work put_bracket($s3,\@a3); put_bracket($s4,\@a4); sub put_bracket { my ($str,$ar) = @_; my $bstr; my $slen = length $ar->[0]; foreach my $subs ( @$ar ) { my $idx = index($str,$subs); my $bgn = $idx; my $end = $idx+$slen+1; substr($str,$bgn,0,"["); substr($str,$end,0,"]"); } print "$str\n"; return ; }

How can I resolve this problem? Am I approaching the problem correctly in the first place? I humbly seek your advice.

Regards,
Edward

In reply to Bracketing Substring(s) in the String by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.