open
open filehandle, filename openfilehandle
,mode
,filename
openfilehandle
,mode
,expr
,list (new in 5.8)
openfilehandle
,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 $
mode
represents 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'
. In addition, you can select
piping to or extracting information from an external program with
'|-'
and '-|'
, respectively. For example:
my $prog = "webster overworked"; open($fh, '-|', $prog) or die("can't open pipe to '$prog': $!");
or, similarly:
my @prog_info = qw(/usr/contrib/bin/webster overworked); open($fh, '-|', @prog_info) or die(...);
A filehandle may also be attached to a process by using a
piped command. If the filename begins with |
, the filename is interpreted as a
command to which output is to be piped. If the filename ends with
a |
, the filename is
interpreted as a command that pipes input to you. You may not have
an open
command that pipes both
in and out.
Any pipe command containing shell metacharacters is passed
to the shell for execution; otherwise, it is executed directly by
Perl. The filename -
refers to
STDIN, and >
refers to
STDOUT. open
returns nonzero
upon success, the undefined value otherwise. If the open
involved a pipe, the return value
happens to be the process ID of the subprocess.
3.144.38.253