use FileHandle; # Add this with the rest of the uses : : # do the filename calculation steps shown above : my $fh=new FileHandle("> $pidfile") or die $!; print $fh "$$"; # Or whatever you want to write undef $fh; #automatically closes the file