my @unsorted_input; while (my $line = ) { if ($line =~ /\A\[/) { # line starts with a bracket if (@unsorted_input) { # if array has entries >>>call your sort routine here<<< print @unsorted_input; undef @unsorted_input; } print $line; # print the header line } else { # line is an entry line push @unsorted_input, $line; } } >> your sort routine << # added code per soonix's correction print @unsorted_input;