foreach my $file ( @files ) { local *FH; open FH, "+< $file" or die "Cannot open $file for updating: $!"; my @data = ; @data = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, get_num( $_ ) ] } @data; seek FH, 0, 0 or die "Cannot seek to start of $file: $!"; print FH @data; close FH; } sub get_num { my $line = shift; my ($num)= $line =~ /t=(\d*)/; # you may need to play with this $num ||= 0; # assign a default to supress "not numeric" errors return $num; }