Sounds like a good reason to use a state variable. Keep file descriptors in a persistent hash.
use 5.010;
use strict;
use warnings;
sub log_msg {
state %fh;
my ($msg, $name) = @_;
unless ($fh{$name}) {
warn "Opening $name\n";
open $fh{$name}, '>', $name or die $!;
print {$fh{$name}} scalar localtime, " Opened file\n";
}
print {$fh{$name}} $msg, "\n";
}
log_msg('Message1', 'first.log');
log_msg('Message2', 'first.log');
log_msg('MessageA', 'second.log');
log_msg('MessageB', 'second.log');
Note the extra set of braces around file descriptors in the print call. This is because printing is a bit picky about what you can use filehandle as an argument.
source
share