Documentation for routine open

Documentation for routine open, assembled from the following types:

role IO

From IO

(IO) sub open

my $fh = open(IO::Path() $path:$r:$w:$a:$rw,

Opens the $path (by default in text mode) with the given options, returning an IO::Handle object.

File mode options

Open the file as read only, e.g.:

my $fh = open("path/to/file":r);

This is the default mode for open.

Write-related methods on the returned IO::Handle object will fail in this mode:

my $fh = open("test");   # the file "test" already exists 
$fh.print("new text\n"); # fails 
CATCH { default { put .^name''.Str } };
# OUTPUT: «X::AdHoc: Failed to write bytes to filehandle: bad file descriptor␤» 

Open the file for writing, creating it if it doesn't exist or overwriting the file if it does exist, e.g.:

my $fh = open("path-to-file":w);

Read-related methods will fail in this mode:

my $fh = open("test":w);
$fh.print("more stuff\n");
$;      # return to the start of the file 
$fh.get();        # fails 
CATCH { default { put .^name''.Str } };
# OUTPUT: «Reading from filehandle failed: bad file descriptor␤» 

Open the file for reading and writing, creating the file if it doesn't exist or overwriting the file if it already exists.

my $fh = open("path-to-file":rw);

Open the file for appending. If the file does not exist, create it. If the file already exists, append data to it.

my $fh = open("path-to-file":a);

Encoding options

Open the file in binary mode (byte mode):

my $fh = open("path-to-file":bin);

A file opened with :bin may still be processed line-by-line, but IO will be in terms of Buf rather than Str types. Default is False, implying text semantics.

The encoding to use if opened in text mode.

# open explicitly as utf8 
my $fh = open("path-to-file"enc => "utf8");
my $fh = open("path-to-file"enc => "utf-8");  # this form also works 
# open with latin1 encoding 
my $fh = open("path-to-file"enc => "latin1");

Defaults to "utf8".

Newline options

nl-in is the marker used to indicate the end of a line of text. Only used in text mode. Defaults to ["\n", "\r\n"] and does not include "\r". nl-out defaults to "\n".

# explicitly use CR-LF as EOL character 
my $fh = open("path-to-file"nl-in => "\r\n");

Whether or not to remove newline characters from text obtained with .lines and .get. Defaults to True.

# don't remove newline characters from input 
my $fh = open("path-to-file"chomp => False);
say $fh.get();     # returns line including newline char 

class IO::Path

From IO::Path

(IO::Path) method open

method open(IO::Path:D: *%opts)

Opens the path as a file; the named options control the mode, and are the same as the open function accepts.