in reply to For loop problem

You are worried about the memory requirements of stuffing the file into a hash, but if the file fits into memory you could stuff it into an array and then use grep to get code which looks a lot cleaner:
use strict; open FILE, "<untested.txt" or die "Blerch: $!\n"; my @contents=<FILE>; close FILE; open OUTPUT ">outputfile" or die "Hcrelb: $!\n"; for my $d (1..10) { print OUTPUT join $\, grep (/^$d/, @contents); } close OUTPUT;
Whether your second requirement is fullfilled with this (lines are written in same order as in inputfile) depends on whether or not grep retains preserves ordering in its input. A quick test on my machine here has indicated that it does, but I don't know whether that's just luck or whether grep is supposed to do it like that. Also note that the above code is untested.

And to top it all off, you can do this even if your file does not fit into memory: use Tie::File to tie the @contents array to the file and away you go.

CU
Robartes-

Update: Clarified things a bit.