http://www.perlmonks.org?node_id=186467

You are all familiar how to match nested balanced parenthesis. But that expressions is easily extendable to larger start and finish markers. Here's how you would match a nested begin/end block.
$re = qr /begin # Start with 'begin', (?: # Followed by (?>[^be]+) # Not a b or e, many times, |b(?!egin) # Or a b not starting 'begin', |e(?!nd) # Or an e not starting 'end', |(??{ $re }) # Or a balanced begin/end block )* # zero or more times end/x; # And an 'end'.