my @dir_list = qw(dept1 dept2 dept3); # actually there are over 40 departments in this list foreach my $dept (@dir_list) { open (DEPTLOG, "+>/data/logs/" . $dept . "current.log"); open (LOGFILE, "/data/logs/access.log"); while () { if (/$dept/) { print DEPTLOG $_; } close(LOGFILE); close(DEPTLOG); } #### my @dir_list = qw(dept1 dept2 dept3); # actually there are over 40 departments in this list my %logs; open (LOGFILE, "/data/logs/access.log"); while () { foreach my $dept (@dir_list) { if (/$dept/) { $logs{$dept} .= $_; } } close(LOGFILE); foreach my $dept (@dir_list) { open (DEPTLOG, "+>/data/logs/" . $dept . "current.log"); print DEPTLOG $logs{$dept}; close (DEPTLOG); }