Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Answer: How do I put bracket on substring(s) of a string?

by monkfan (Curate)
on Aug 27, 2005 at 03:27 UTC ( #487088=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > How do I put bracket on substring(s) of a string? - Answer contributed by monkfan

This is an attempt to save a thread in SoPW which I thought can be useful for others.

There are already incredible answers in the thread, so feel free to check in SoPW. Please don't misunderstand me. I honestly think this can be useful. I don't mean to boost my XP here, or in that thread which I posted.

One possible answers is given by good sgifford

#!/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); put_bracket($s1,\@a1); put_bracket($s2,\@a2); put_bracket($s3,\@a3); put_bracket($s4,\@a4); sub put_bracket { my( $str, $ar ) = @_; foreach my $subs ( @$ar ) { # Construct a regexp with [\[\]] between all the letters my $newsub = join '[\[\]]?', split //, $subs; $str =~ s/($newsub)/[$1]/g; } # Now de-nest the brackets in the string my $depth = 0; my $newstr = ''; foreach my $c ( split //, $str ) { if ( $c eq '[' ) { $newstr .= $c if $depth++ == 0; } elsif ( $c eq ']' ) { $newstr .= $c if --$depth == 0; } else { $newstr .= $c; } } return $newstr; }
More can be found here. Don't vote my root posting but vote those remarkable answers you will find there.

Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2016-10-23 02:57 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (300 votes). Check out past polls.