The problem is that once you've added the brackets,
index doesn't match anymore. Regular expressions can deal with this more easily. This code allows optional brackets between letters to find the substrings, then it "de-nests" the brackets to get the results you give above.
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;
}
}
print "$newstr\n";
return ;
}