in reply to regex matches more than I want

.* is very greedy. Try this instead:
print $#{[$lines =~ /aaa(.*?)bbb(.*?)ccc\s*dddd/gsi]} + 1 . "\n";

Update:
I went under the assumption that:
$lines = "aaa xxxxxxx bbb ccc dddd";
print  $#{[$lines =~ /aaa(.*?)bbb(.*?)ccc\s*dddd/gsi]} + 1 . "\n"; will return 2.

If
$lines = " aaa xxxxxxx bbb ccc dddd aaa xxxxxxxxxxxxxxxxxxxxx xxxxxxx bbb xxxxxxxxxxxxxxxxxxxxx xxxx xx ccc dddd";
print  $#{[$lines =~ /aaa(.*?)bbb(.*?)ccc\s*dddd/gsi]} + 1 . "\n"; will return 4.

If you use
$lines = " aaa xxxxxxx bbb ccc dddd aaa xxxxxxxxxxxxxxxxxxxxx xxxxxxx bbb xxxxxxxxxxxxxxxxxxxxx xxxx xx ccc dddd"; print $#{[$lines =~ /aaa.*?bbb.*?ccc\s*dddd/gsi]} + 1 . "\n";
It will return 2.
I'm not sure if thes helps or not but my guess is the last solution I show is what you want.