Global file descriptors will remain until your program exits. This may be bad, but since you probably shouldn't use global file descriptors, this is not a problem.
The lexical file descriptors with my are equal to close d when their area remains / their number of links drops to zero.
If the file descriptor name is reused, the previous file descriptor close d is implicit. The following script uses the same file descriptor to print the first five lines of any number of files:
my $fh; foreach my $filename (@ARGV) { open $fh, "<", $filename or die "Can't open $filename";
When working with files, explicitly closing FH does not matter. However, this is important when performing IPC. Closing the write tip in the tube indicates the EOF at the end of the read.
When fork ing, all unused file descriptors must be closed because they are duplicated during forking. This means that closing the pipe in one process may not send the desired EOF, because the same channel is still open in the corresponding process.
Here is a program that demonstrates the importance of close in IPC:
pipe my $out, my $in or die $!; if (fork()) {
The result of this program is numbers from 1 to 5. Then the child element closes its end in the pipe, causing SIGPIPE in the parent element. While the parent is dying, the child is delayed for 5 seconds until he dies.
This works because the parent has closed the read end for the pipe. If close $out is removed from the parent, SIGPIPE will not triggerd, and the program prints the numbers ad infinitum.