file-io beginner

How to write to a file safely in Perl

Question

What is the correct way to write data to a file in Perl with error handling?

Always use the three-argument open with error checking and lexical filehandles:

use strict;
use warnings;
use autodie;  # Automatic error handling

# Method 1: Manual error checking
open my $fh, '>', 'output.txt' or die "Cannot open output.txt: $!";
print $fh "Line 1\n";
print $fh "Line 2\n";
close $fh or die "Cannot close output.txt: $!";

# Method 2: Using autodie (recommended)
open my $out, '>', 'data.txt';
print $out "Hello World\n";
close $out;

# Append mode
open my $append, '>>', 'log.txt' or die $!;
print $append "Log entry\n";
close $append;

# One-liner to write
# perl -e 'print "text\n"' > file.txt

The autodie pragma automatically adds error checking to file operations, making code cleaner and safer.

Was this helpful?

Related Questions