use warnings; use strict; use FileHandle; my @filenames = map { $_ . '.txt' } 1 .. 3; my @handles = map { FileHandle->new($_, '>') } @filenames; while () { my @cols = split /,/; $handles[$cols[1]-1]->print($_); } __DATA__ 10234,1,34234,342,453,34535,3453,3464 12123,1,23432,4353,44645,45654,45645,657 2123345,2,35435,3453,454,56567,56756,567567 3234353,2,34534,4564,567567,56757,56575,24234 33453,3,45464,4564564,45645,645645,54564,56456