Name

open

Synopsis

open filehandle, filename

open filehandle, mode, filename

open filehandle, mode, expr, list (new in 5.8)

open filehandle, mode, reference (new in 5.8)
                  

Opens the file given by filename and associates it with filehandle. If filehandle is omitted, the scalar variable of the same name as the filehandle must contain the filename. (And you must also be careful to use or die after the statement rather than || die, because the precedence of || is higher than list operators such as open.)

If filename is preceded by either < or nothing, the file is opened for input (read-only). If filename is preceded by >, the file is opened for output. If the file doesn’t exist, it will be created; if the file exists, it will be overwritten with output using >. Preceding the filename with >> opens an output file for appending. For both read and write access, use a + before < or >.

If you choose to use the three-or-more-arguments form of open, you can use separate mode and filename arguments, such as open($ fh , $ mode , $ filename ), in which $ moderepresents an open mode or pipe. For example:

my $mode = '+<';
my $filename = 'whatever.txt';
open(FH, $mode, $filename)
    or die("can't open $filename: $!");

As covered in Chapter 4, you can build Perl 5.8 and newer with PerlIO support, which offers additional features for your system’s I/O (STDIO). This allows you to do neat things, such as specify utf-8 as your default encoding for all of your I/O, or set your default line endings with 'crlf'

Get Perl in a Nutshell, 2nd Edition 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.