in reply to matching several lines

If you $/ = 'BBBBBB';, then you can loop on if ( /AAAAAA(.*?)$/ ) rather than your inner while.

Revised Made code a little tighter.