g in your regex means that it'll happen globally, so every instance will get processed, so line 7 actually gets fired multiple times. It APPEARS that since the line is getting modified after the current evaluation, that gets caught and processed. Testing seems to confirm this, as when you replace the IDs with 5 it works as expected. As to an actual reason as to WHY this is, I'd be interested in knowing myself. I assume that backtracking has something to do with this. perlre's section on backtracking may explain it better.
See
Choroba's response. I missed the quite obvious fact that it was calling itself.