find_encoding#

Look up an encoding by name and return an object you can call methods on.

Synopsis#

my $enc = find_encoding($name);
my $bytes  = $enc->encode($string);
my $string = $enc->decode($bytes);
my $canon  = $enc->name;

What you get back#

A blessed encoding object: Encode::utf8 for the UTF-8 family, Encode::Unicode for UTF-16 and UTF-32, Encode::XS for the table-driven encodings, or the class of whichever module defines the encoding. If the name cannot be resolved, find_encoding returns undef.

The object provides the Encode::Encoding methods, among them encode, decode, name (returns the canonical string), and perlio_ok (true when the :encoding() layer can use the encoding). renew returns the same object for an Encode::XS encoding and a copy for the others.

Name resolution is case-insensitive and treats - and _ interchangeably. “utf-8”, “UTF-8”, and “utf_8” all resolve to the same object; “UTF8” without the dash is the lax utf8 encoding, a different one.

Examples#

Cache an encoding object and reuse it in a loop:

my $enc = find_encoding('UTF-8');
while (my $line = <$fh>) {
    my $string = $enc->decode($line);
    # ... work with $string ...
}

Query by alias:

my $enc = find_encoding('latin1');
print $enc->name;   # iso-8859-1

Edge cases#

  • Unknown names return undef after falling back to Encode::Alias::find_alias for aliases registered with define_alias.

  • An Encode::XS object is a blessed scalar reference with no fields; the others are blessed hashes with a Name key. Code that pokes inside is not portable across encodings.

Differences from upstream#

Fully compatible with upstream.

See also#

  • resolve_alias - get just the canonical name string.

  • encodings - list every name the registry knows.

  • encode, decode - the function forms, if you don’t want to hold an object.