in reply to die command while other files are opened

The information provided earlier by Athanasius is quite valid and I won't repeat it here. However, I'll also add that under normal conditions, file-handles will auto-close when they fall out of scope (demo code for this is below.) However, it's unwise to rely on this as you cannot test that the closing finished properly.

Because buffers may not always be flushed through the perlio layer, you don't actually know that the content you sent to the handle really got written to disk. You might call the IO/Handle method $fh->flush() to try and force buffers to be flushed early, or simply verify you set autoflush on the file handle to flush buffers as soon as practical.

The code below explicitly sets autoflush (using the $| variable) to 0, or false. In recent-ish versions of IO::Handle, autoflush tends to be turned on by default.

How to use this example: you should open 2 terminals in the path that you save this program. Then start the program, and once it is started, run the command tail -f out.log to watch the realtime progress of the output file in another terminal. What you will find is that with autoflush off, nothing is written until the filehandle falls out of scope. Note that we never closed it, but this also means we have no way of knowing if the data really got written out to disk (and thus we couldn't print an error message to STDERR about such a problem.

Bonus points: turn autoflush on in this code, and see what changes. Figure out why.

Here's the sample code:

use strict; use warnings; # Scope some work { open(my $fh, ">", "out.log") or die "Open failed"; my $oldfh = select($fh); $| = 0; select($oldfh); # Print that we opened the file, then sleep. # This gives a caller time to do a tail -f in another window. print "File opened, in out.log\n"; print "If you want, begin your tail now.\n"; print "10 second sleep..\n"; sleep 10; print "Now printing lines..\n"; # Now write 5 lines, one at a time. 1 second sleeps between. for (1..5) { print $fh "$_\n"; print STDOUT "I just printed line $_\n"; sleep 1 } # We will NOT close the $fh explcitly. # When it falls out of scope, the buffers will be flushed. # HOWEVER, we cannot know if this worked. # It could be that the disk filled up or some other error. # We do not know unless we call close() explicitly! } # Sleep a bit to demonstrate the buffer is flushed before program exit print "All done printing lines. The handle is out of scope now.\n"; print "We're sleeping for 5 seconds..\n"; sleep 5; print "All done!\n"; exit 0;