while () { if (/(\d+) matches\)/) { # keep this in a list we'll sort later push @list, [ $1, $_ ]; } else { # same case as before, write it to the log print LOG; } } # Now print out the list we built before in sorted order foreach (sort { $a->[0] <=> $b->[0] } @list ) { print $_->[1]; }