Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by Roy Johnson (Monsignor)
on Sep 10, 2008 at 17:49 UTC ( [id://710418]=note: print w/replies, xml ) Need Help??


in reply to How do I put bracket on substring(s) of a string?

#!perl use strict; use warnings; my @testdata = (['CCCATCTGTCCTTATTTGCTG', [qw(ATCTG ATTTG)]] ,['ACCCATCTGTCCTTGGCCAT', [qw(CCATC)]] ,['CCACCAGCACCTGTC', [qw(CCACC CCAGC GCACC)]] ,['CCCAACACCTGCTGCCT', [qw(CCAAC ACACC)]]); for (@testdata) { my ($str, $pats) = @$_; print put_bracket($str, @$pats), "\n"; } sub put_bracket { my $str = shift; # Combine multiple match strings into alternations my $rx = join '|', @_; my @brackets; # Store bracket points for every match while ($str =~ /(?=($rx))/g) { push(@brackets, [$-[0], length($1)+$-[0]]); } # Condense overlapping brackets for my $i (0..$#brackets-1) { if ($brackets[$i][1] >= $brackets[$i+1][0]) { $brackets[$i+1][0] = $brackets[$i][0]; @{$brackets[$i]} = (); } } # Apply the brackets (from back to front) while (@brackets) { my $b = pop @brackets; next unless @$b; substr($str, $b->[1], 0) = ']'; substr($str, $b->[0], 0) = '['; } return $str; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-18 05:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found