Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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

by Roy Johnson (Monsignor)
on Sep 10, 2008 at 17:49 UTC ( #710418=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 Roy Johnson

#!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?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2017-03-01 19:20 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (428 votes). Check out past polls.