in reply to $1 not "freezing" in an addition
Does it work better if you "unreverse" the if condition?
if(s/\(#:(\d+)\)/#/) { return $1 + distance($_); }
As I don't have the whole code, it's a bit difficult to test. And it's just a hunch.
In Section
Seekers of Perl Wisdom