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


in reply to Reading particular line which repeats itself many times in text

I don't know whether there is a fancy regular expression for this but in case where there are blocks I always use split (I consider it safer).
my @begin_blocks=split /BEGIN $name/,$string_containing_blocks; my $block=$begin_blocks[1]; $block=~s/END\s*$//;
If there is no match '' is returned (since @begin_blocks now has only the zero index element: the string itself). This won't work if BEGIN blocks can contain the string 'BEGIN' inside them. If this is necessary you can use an escape sequence: replace all 'BEGIN'-s inside the block with 'BEGIN_'. If such a coding is used the search looks like this (add one line for decoding BEGIN_):
my @begin_blocks=split /BEGIN $name/,$string_containing_blocks; my $block=$begin_blocks[1]; $block=~s/END\s*$//; $block=~s/BEGIN_/BEGIN/g;