in reply to substr out of str error - but why?

First off, it would really help if you could provide an SSCCE.

With the code provided it is far from clear what you are trying to do, or where the error is occurring.

My first question would be: at what line of the provided code is the error actually occurring?

My second question would be: is length($opposite{$side1}) always 1, or is it sometimes 0, or more than 1?

My third question would be: does your real code have use strict and use warnings enabled?

Then I would observe that the code would be easier to read if you used //x on your regexp, and if you had my $length = $end - $start + 1 and used that throughout. It would also be useful to add more instrumentation: show $type in each iteration, show the full string before and after each change, show all the parameters to substr() before each invocation.

I suspect that with better instrumentation the answer will be obvious to you, but if you want help from us you need to help us to help you. And that starts with a Short, Self-Contained, Correct Example.

Hugo