file-io beginner

How to write to a file in Perl?

Question

How to write to a file in Perl?

Writing to a file in Perl is a fundamental task that you will often perform when working with external data. Perl's built-in file handling functions make it straightforward to open, write to, and close a file.

Basic Concepts

  • Filehandles: In Perl, a filehandle is a special variable used for input/output operations. It is often represented by an uppercase bareword (like FH) or a scalar variable.
  • Opening files: Use the open function to connect a filehandle to a file. To write, open the file with the `>` mode for overwriting or `>>` for appending.
  • Printing to filehandles: Use print with a filehandle to send output to that file instead of STDOUT.
  • Closing files: Always close the filehandle with close to flush and free the file resources.

Example: Writing to a File

Below is a simple Perl script that opens a file, writes some text, and closes the file. You can run this as-is and it will create or overwrite output.txt in the current directory.

#!/usr/bin/perl
use strict;
use warnings;

my $filename = 'output.txt';

# Open the file for writing (overwrite mode)
open(my $fh, '>', $filename) or die "Cannot open $filename for writing: $!";

# Write some content to the file
print $fh "Hello, this is a line of text.\n";
print $fh "Perl file writing example.\n";

# Close the filehandle
close($fh) or warn "Could not close $filename: $!";

print "Data written to $filename\n";

Explanation

  • open(my $fh, '>', $filename): The > indicates write mode, which overwrites the file if it exists or creates it otherwise.
  • print $fh "text\n": Prints the string followed by newline to the opened filehandle $fh.
  • close($fh): Closes the filehandle, ensuring all data is written to disk.
  • Using strict and warnings helps catch errors early in your script.

Additional Tips and Gotchas

  • To append to an existing file instead of overwriting, use '>>' mode in open.
  • Always check the return value of open with or die to handle errors gracefully.
  • Use lexical filehandles (my $fh) instead of bareword filehandles for better scoping and safety (introduced in Perl 5.6).
  • Remember that print to a filehandle differs from print to STDOUT; specifying the filehandle explicitly directs output to the file.
  • Perl context: print doesn't return the number of bytes written, it returns true on success. For detailed I/O errors, rely on open and close error checks.

File handling in Perl illustrates the philosophy of TMTOWTDI ("There's More Than One Way To Do It"), but this approach is the most common pattern for writing text files safely and cleanly.

Verified Code

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

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

Was this helpful?

Related Questions