use strict; use warnings; #https://www.perlmonks.org/?node_id=525392 my $lineNUM; while () { if ($lineNUM = /^BEGIN_TAG/.../^END_TAG/ ) { print "#$_" if $lineNUM =~ /^\d+$/; print "#\n" if $lineNUM =~ /E0/; } } =Prints #BEGIN_TAG_110 #In this text I'm interested in. #It can consist of several lines. Until the end tag. # #BEGIN_TAG_237 #I need this text. # =cut __DATA__ Any text is in this document. But I'm only interested in the text between a beginning and an end tag. BEGIN_TAG_110 In this text I'm interested in. It can consist of several lines. Until the end tag. END_TAG and any other things I'm not interested in until the next beginning tag starts. Any other text. BEGIN_TAG_237 I need this text. END_TAG More text ...