use strict; use warnings; my $count; while (my $line = ) { if ($line =~ m/endloop/) { $count --; } elsif ($line =~ m/loop/) {#don't put this before endloop, as endloop itself matches loop $count ++; } elsif ($line =~ m/warn/) { print $line if ($count > 0); } } __DATA__ begin loop warn('xxx'); endloop; loop null; loop warn('AAA'); endloop; endloop; loop loop warn('BBB'); endloop; warn('rrr'); endloop; begin loop endloop; warn('yyy'); end; warn('zzz'); end;