use strict; open FH, "foo" or die "Can't open: $!"; my @recs; while () { chomp; push @{$recs[int(($.-1) / 5)]}, $_; } close FH or die "Can't close: $!"; open FH, ">foo.new" or die "Can't open: $!"; for my $ref (@recs) { # break up the city, state, zip into 3 parts my($city, $state, $zip); if ($ref->[2] =~ /(.*?),\s(.*?)\s(.*)/) { ($city, $state, $zip) = ($1, $2, $3); } # join it all together into a pipe-separated # record, then write it out my $new = join "|", @{$ref}[0,1], $city, $state, $zip, @{$ref}[3,4]; print FH $new, "\n"; } close FH;