Opening a File

Problem

You want to read or write to a filename from Perl.

Solution

Use open for convenience, sysopen for precision, or the IO::File module to get an anonymous filehandle.

The open function takes two arguments: the filehandle to open and one string containing the filename and special characters indicating how to open it (the mode):

open(SOURCE, "< $path")
    or die "Couldn't open $path for reading: $!\n";

open(SINK, "> $path")
    or die "Couldn't open $path for writing: $!\n";

The sysopen function takes three or four arguments: filehandle, filename, mode, and an optional permissions value. The mode is a number constructed from constants provided by the Fcntl module:

use Fcntl;

sysopen(SOURCE, $path, O_RDONLY)
    or die "Couldn't open $path for reading: $!\n";

sysopen(SINK, $path, O_WRONLY)
    or die "Couldn't open $path for writing: $!\n";

The IO::File module’s new method accepts both open and sysopen style arguments and returns an anonymous filehandle. The new method also accepts a mode in the style of fopen (3):

use IO::File;

# like Perl's open
$fh = IO::File->new("> $filename")
    or die "Couldn't open $filename for writing: $!\n";

# like Perl's sysopen
$fh = IO::File->new($filename, O_WRONLY|O_CREAT)
    or die "Couldn't open $filename for writing: $!\n";

# like stdio's fopen(3)
$fh = IO::File->new($filename, "r+")
    or die "Couldn't open $filename for read and write: $!\n";

Discussion

All input and output goes through filehandles, whether filehandles are mentioned or not. Filehandles ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.