Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

open

Opens a file, pipe, or duplicates a file descriptor, associating it with a filehandle.

Supports both the 2-argument form (mode embedded in the filename string) and the 3-argument form (separate mode and filename). The 3-argument form is preferred as it avoids shell metacharacter issues.

ModeMeaning
<Read
>Write (truncate)
>>Append
+<Read/write (existing file)
+>Write/read (truncate)
|-Pipe to command
-|Pipe from command
>& / <&Dup filehandle
>&= / <&=Dup by file descriptor number

In-memory I/O is supported via scalar references: open $fh, '>', \$buf.

Returns 1 on success, undef on failure. Sets $! on error.

Synopsis

open(my $fh, '<', $filename);       # read
open(my $fh, '>', $filename);       # write (truncate)
open(my $fh, '>>', $filename);      # append
open(my $fh, '+<', $filename);      # read/write
open(my $fh, '|-', @cmd);           # pipe to command
open(my $fh, '-|', @cmd);           # pipe from command
open(my $fh, '>&', $other_fh);      # dup for writing
open(my $fh, '<', \$scalar);        # in-memory I/O
open(FH, "<$filename");             # 2-arg form

See Also

close, binmode, print, read, sysopen, perlopentut