1. Perl
  2. builtin functions
  3. here

close function - close file handle

Use the close function to close the filehandle .

close $fh;

In a little more detail, when the close function is called, the current buffer is flushed and then the filehandle is closed.

Is it necessary to close the file handle with the close function?

Is it necessary to close the file handle with the close function after opening the file with the open function? It is not always necessary.

In general, open the file as follows:

open(my $fh, '<', $file);

"$Fh" is a lexical variable. Then, when the scope is over, the lexical variable are released. Then, when it is released, the close function is automatically called. Files are also one scope. So if a lexical variable has a filehandle assigned to it, you usually don't need to call the close function.

Here are some examples when you need to use the close function.

When a file handle is assigned to a type glob or symbol

Filehandles can also be assigned to typeglobs and filehandles. In old source code, you will often see the following open.

# Type glob
open(* FH, '<', $file)

# Symbol
open(FH, '<', $file)

In such a case, if you do not explicitly close it, the file handle will remain open even after the scope ends, so let's close it. If you have a short program and the program quits quickly, Global Destruction will close the file, so you don't have to close it, but it's a good idea to do so.

If you want to flush the buffer immediately and close the filehandle

The close function flushes the buffer and then closes the file handle. A buffer is data that has not yet been written to a file.

Suppose you open a filehandle in write mode and write data with the print function. However, this data is not written immediately, but is stored in the buffer. This is for efficiency. After a certain amount of buffer is accumulated, it is written.

In such a case, if you want to flush immediately, you can use the close function.

When you need to open a pipe, socket, etc. and explicitly close it

If you use the fork and open functions to open multiple pipes, sockets, etc., you may want to close only the write side or only the read side. In that case, explicitly call the close function.

Related Informatrion