my $company = "unlikelyname"; my $OUT; while (<$file>) { my @f = split '\s+', $_; if ($f[0] !~ /$company/) { close $OUT if defined $OUT; open $OUT, ">", "$f[0].txt" or die "blabla $!"; $company = $f[0]; } my @ymd1 = split ',',$f[4] //= $prev_mth_end; my @ymd2 = split ',',$f[5] //= $prev_mth_end; # ... printf OUT $pfmt, @f[0..3], fmt_mdy($f[4]), fmt_mdy($f[5]), $diff, $free, $waive, fmt_curr($cost), $stg_chg, $sw_chg, $f[6], fmt_curr($cartot), $comment; }