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
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?