#! perl use strict; use warnings; my @carslist = qw(DATSUN_BLUE TOYOTA_MAROON ELANTRA_YELLOW); my %cars; for (@carslist) { unless (exists $cars{$_}) { my $file = 'tmp/' . $_ . '.txt'; open(my $fh, '>', $file) or die "Cannot open file '$file' for writing: $!"; $cars{$_} = $fh; } } my $pattern = join '|', @carslist; $pattern = qr/$pattern/; my @strings; while () { chomp; my @fields = split; if (($fields[1] eq '1' || $fields[1] eq '0') && /$pattern/) { push @strings, $_; print { $cars{$fields[4]} } $fields[0], ',', $fields[4], "\n" if /engineer/ && !/,-,/; } } for (@carslist) { close $cars{$_} or die "Cannot close file '$_': $!"; } print "Strings:\n"; print "$_\n" for @strings; __DATA__ 1250 1 engineer office DATSUN_BLUE office 67 page30 text 1500 1 billing office MERCEDES_TAN office 98 page 40 txt 1500 7 billing office JAGUAR_BLACK office 98 page 40 txt 1250 0 engineer office ELANTRA_YELLOW office 66 page50 txt 1250 1 engineer office DATSUN_BLUE office 67 page30 text