If I have a subroutine that opens a file what is the best way to ensure it opens it only upon the first time the subrountine is called? I have this but not sure if its best practice:
{
my $count = 0;
sub log_msg {
my ($msg,$name) = @_;
if ($count == 0) {
my $log_file_name = "/tmp/" . $name;
open my $log_fh,">",$log_file_name or croak "couldn't open $log_file_name : $!";
print $log_fh "$timestamp: created and opened $log_file_name\n";
}
$count++;
}
}
Sounds like a good reason to use a state variable. Store the filehandles in a persistent hash.
Note the extra set of braces around the filehandles in the print call. That’s because print is a bit picky about what you can use as its filehandle argument.