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); }