Perl File Open: Creating, Reading and Writing to Files in Perl

Dealing with files in Perl is very easy once you get used to the slightly odd syntax. Here are some examples to get you started.

Open a File in Perl



To open a file in Perl, just the open() subroutine.

Here's an example of a program that opens a file, reads the file one line at a time and prints each line to the terminal.

use strict;
use warnings; 

# Put the file name in a string variable
# so we can use it both to open the file
# and to refer to in an error message
# if needed.
my $file = "temp.txt";

# Use the open() function to open the file.
unless(open FILE, $file) {
    # Die with error message 
    # if we can't open it.
    die "\nUnable to open $file\n";
}

# Read the file one line at a time.
while(my $line = <FILE>) {
    # We'll just print the line for now.
    print $line;
}

# close the file.
close FILE;




If you want to read binary files in Perl, you need to set the binmode on the file handle.



The following example also illustrates how you can read an entire file in one go. Of course if the file is large and your memory limited, this might be a bad idea. Usually you probably want to read a file in chunks, writing out the chunks to another file as you go.

use strict;
use warnings; 

# Put the file name in a string variable
# so we can use it both to open the file
# and to refer to in an error message
# if needed.
my $file = "temp.bin";

# Use the open() function to open the file.
unless(open FILE, $file) {
    # Die with error message 
    # if we can't open it.
    die "\nUnable to open $file\n";
}

# Tell Perl we want to read data as binary.
binmode(FILE);

# Get rid of the line separator.
# This allows us to read everything
# in one go.
undef $/;

# Read the entire file. If you don't want
# to read all of it at once, you need the
# read() subroutine.
my $contents = <FILE>;

print "Read " . length($contents) . " bytes\n";

# close the file.
close FILE;




Read 520 bytes




If you are dealing with a text file, it's often useful to set the file record separator $/ (set to the newline character by default) to some other value, such as a particular closing XML tag. Undefining it altogether, as in the above example, causes the entire file to be read at once.

Creating Files In Perl



To create a file in Perl, you also use open(). The difference is that you need to prefix the file name with a > character to make Perl open the file for writing. Any existing file with the name you supply to open() will be overwritten, unless you specify >> instead, which opens a file for appending.

This program creates a file called "temp.txt" and writes two lines to it.

use strict;
use warnings; 

# Put the file name in a string variable
# so we can use it both to open the file
# and to refer to in an error message
# if needed.
my $file = "temp.txt";

# Use the open() function to create the file.
unless(open FILE, '>'.$file) {
    # Die with error message 
    # if we can't open it.
    die "\nUnable to create $file\n";
}

# Write some text to the file.

print FILE "Hello there\n";
print FILE "How are you?\n";

# close the file.
close FILE;




Open A Text File, Process It and Write to Another File



Here's a complete example of a program that opens a text file in Perl, reads it line by line, carries out processing on each line and writes the results to another file.

# Always define these two at the tops of
# your scripts.
use strict;
use warnings; 

# This turns off output buffering.
# Useful for real-time display of
# progress or error messages.
$|=1;

# This is for getting command-line options.
# Could alternatively use @ARGV instead.
use Getopt::Std;

# Return a usage message. Usually we'd indent the
# contents of a subroutine, but here we can't since
# that would affect the usage message.
sub usage {
return q|

usage:
    process.pl -i <input file> -o <output file>
    
Reads all lines in <input file>, changes all occurences of
'dog' to 'cat' and writes the results to <output file>.

<input file> itself is not changed.

|;
}

sub main {
    # Collect the -i and -o options from the command line.
    my %opts;
    
    # The colons specify that the preceeding flags take
    # arguments (file names in this case)
    getopts('i:o:', %opts);
    
    # Check we got the flags and arguments we need.
    unless($opts{'i'} and $opts{'o'}) {
        die usage();
    }
    
    # Now we've got the input and output file names.
    my $input = $opts{'i'};
    my $output = $opts{'o'};
    
    # Try to open the input file.
    unless(open INPUT, $input) {
        die "\nUnable to open '$input'\n";
    }
    
    # Try to create the output file
    # (open it for writing)
    unless(open OUTPUT, '>'.$output) {
        die "\nUnable to create '$output'\n";
    }
    
    # Read one line at a time from the input file
    # till we've read them all.
    while(my $line = <INPUT>) {
    
        # Change dog to cat
        $line =~ s/dog/cat/ig;
        
        # Write the line to the output file.
        print OUTPUT $line;
        
        # Print a progress indicator.
        print '.';
    }
    
    # Close the files.
    close INPUT;
    close OUTPUT;
    
}

main();