use strict; use warnings; my @lines; while () { my ($first, $sort, $second, $tail) = m/^(\w+)\s+(\d+)\s+(\w+)(.*)$/; die "Unable to match any lines:$!\n" if ! defined $tail; push @lines, [$sort, $first, $second, $tail]; } print join "\n", map {"$_->[1] $_->[0] $_->[2]$_->[3]"} sort {$a->[0] <=> $b->[0]} @lines; __DATA__ a 0 f g j k b 4 y h t e e e c 1 n s v c x d 3 f f f #### a 0 f g j k c 1 n s v c x d 3 f f f b 4 y h t e e e