#!/usr/bin/perl use v5.28; use warnings qw( FATAL all ); @ARGV or die "Usage: $0 PATTERN [FILES...]"; my $pattern = shift @ARGV; $pattern = qr/$pattern/o; my @where; my $wi = 0; while(<>) { s/\s*\z//; length or next; my $indent = /^(\s+)/ && $1; while( @where && $where[-1] =~ /^$indent/ ) { pop @where; $wi = @where if $wi > @where; } push @where, $_; if( /$pattern/ ) { say $_ for @where[ $wi .. $#where ]; $wi = @where; } } continue { if( eof ) { @where = (); $wi = 0; } }