file-io beginner

How to close a filehandle in Perl?

Question

How to close a filehandle in Perl?

Closing a filehandle in Perl is a fundamental part of file I/O (input/output) operations. After you finish reading from or writing to a file, you should close the filehandle to free up system resources and ensure all data is properly flushed to disk.

How to Close a Filehandle

In Perl, you close a filehandle using the close function. The syntax is:

close FILEHANDLE;

Here, FILEHANDLE can be a bareword (like FILE), a scalar holding a reference to a filehandle (preferred in modern Perl), or a glob.

Example: Opening and Closing a Filehandle

use strict;
use warnings;

# Open a file for writing
open my $fh, '>', 'output.txt' or die "Cannot open output.txt: $!";

print $fh "Hello, Perl filehandles!\n";

# Close the filehandle
close $fh or warn "Close failed: $!";
print "Filehandle successfully closed.\n";

This example demonstrates:

  • Opening a filehandle $fh for writing using the three-argument open, which is safer and recommended over older styles.
  • Printing some data to the file.
  • Closing the filehandle with close and checking for errors (e.g., disk full or permission problems).

Details and Good Practices

  • Always check the return value of close when writing files. A failed close means data might not have been completely flushed.
  • Use lexical filehandles (e.g., my $fh) instead of package globals (FILE) whenever possible; they localize the handle and avoid namespace pollution.
  • Perl automatically closes open filehandles when your program ends or when the filehandle variable goes out of scope, but explicitly closing allows you to detect errors immediately.
  • You can also close standard filehandles like STDIN, STDOUT, and STDERR.
  • close will return true on success and false on failure. Use or die or or warn to catch errors.

Common Pitfalls

  • Not checking the return value of close can mask errors.
  • Trying to use a filehandle after it is closed will cause runtime errors.
  • Using a bareword filehandle without my can cause namespace collisions in larger scripts.
  • Not flushing buffers explicitly can cause partial writes; closing the handle ensures flushing.

Summary

Closing a filehandle in Perl is done with the close function, which safely ends file access and frees resources. Always check the return value of close to catch errors, and prefer lexical filehandles for safer, idiomatic Perl code.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 5ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions