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;