Documentation for routine encoding

Documentation for routine encoding, assembled from the following types:

class IO::Handle

From IO::Handle

(IO::Handle) method encoding

Defined as:

multi method encoding(IO::Handle:D: --> Str:D)
multi method encoding(IO::Handle:D: $enc --> Str:D)

Returns a Str representing the encoding currently used by the handle, defaulting to "utf8". Nil indicates the file handle is currently in binary mode. Specifying an optional positional $enc argument switches the encoding used by the handle; specify Nil as encoding to put the handle into binary mode.

The accepted values for encoding are case-insensitive. The available encodings vary by implementation and backend. On Rakudo MoarVM the following are supported:


The default encoding is utf8, which undergoes normalization into Unicode NFC (normalization form canonical). In some cases you may want to ensure no normalization is done; for this you can use utf8-c8. Before using utf8-c8 please read Unicode: File Handles and I/O for more information on utf8-c8 and NFC.

Implementation may choose to also provide support for aliases, e.g. Rakudo allows aliases latin-1 for iso-8859-1 encoding and dashed utf versions: utf-8 and utf-16.

with 'foo'.IO {
    .spurt: "First line is text, then:\nBinary";
    my $fh will leave {.close} = .open;
    $fh.get.say;         # OUTPUT: «First line is text, then:␤» 
    $fh.encoding: Nil;
    $fh.slurp.say;       # OUTPUT: «Buf[uint8]:0x<42 69 6e 61 72 79>␤» 

class IO::CatHandle

From IO::CatHandle

(IO::CatHandle) method encoding

Defined as:

multi method encoding(IO::CatHandle:D:)
multi method encoding(IO::CatHandle:D: $new-encoding)

Sets the invocant's $.encoding attribute to the provided value. Valid values are the same as those accepted by IO::Handle.encoding (use value Nil to switch to binary mode). All source handles, including the active one will use the provided $.encoding value.

(my $f1 = 'foo'.IO).spurt: 'I ♥ Perl';
(my $f2 = 'bar'.IO).spurt: 'meow';
with $f1$f2 {
    # .encoding is 'utf8' by default: 
    .readchars(5).say# OUTPUT: «I ♥ P␤» 
    .encoding: Nil# switch to binary mode 
    .slurp.say# OUTPUT: «Buf[uint8]:0x<72 6c 6d 65 6f 77>␤»