#!/usr/bin/env perl use strict; use warnings; use autodie; while () { print; /^B (\S+)/ && read_input($1); } sub read_input { my ($file) = @_; open my $fh, '<', $file; while (<$fh>) { print; /^B (\S+)/ && read_input($1); } close $fh; return; } #### m m n n o o B pm_1081744_tst.bat B pm_1081744_tst.bat a b c B pm_1081744_tst2.bat z y x w 1 2 3 p p q q r r