$/ = ""; # input record separator set to empty string my $last_rec; while (<>) { # each record is terminated by /\n{2,}/ if ( /^def/ ) { print $last_rec.$_ if ( $last_rec ); } else { $last_rec = $_; } }