Reading and writing a file with Perl

learn.perl.org
 

Writing to a file

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

use Path::Class;
use autodie; # die if problem reading or writing a file

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("file.txt"); # /tmp/file.txt

# Get a file_handle (IO::File object) you can write to
my $file_handle = $file->openw();

my @list = ('a', 'list', 'of', 'lines');

foreach my $line ( @list ) {
    # Add the line to the file
    $file_handle->print($line . "\n");
}

Appending to a file

# As above but use open('>>') instead of openw()
my $file_handle = $file->open('>>');

Reading a file

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

use Path::Class;
use autodie; # die if problem reading or writing a file

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("file.txt");

# Read in the entire contents of a file
my $content = $file->slurp();

# openr() returns an IO::File object to read from
my $file_handle = $file->openr();

# Read in line at a time
while( my $line = $file_handle->getline() ) {
        print $line;
}

Path::Class makes working with directories (Path::Class::Dir) and files (Path::Class::File) clean and easy to do. Try to work with file() or dir() objects throughout your code, but remember if you are calling other Perl modules you will often need to convert the object to a string using 'stringify':

    $file->stringify();
    $dir->stringify();
    

autodie forces many functions to die with a useful error message (instead of returning undef) if they fail. This makes for cleaner code. To check for and catch errors use Try::Tiny.