XML technologies / XML / Perl & XML / XML basics: Reading and writing / Character sets and encodings
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Whatever your output method, remember character sets and encodings: the protocol XML uses to represent your language’s symbols, whether alphabetic letters, ideographs or diacritics. Encodings can be among XML programming’s hardest aspects, surprisingly so for Western European and US programmers: ISO 8859-1 and ASCII are simple, leaving them least familiar with more complex systems’ pitfalls.
XML may name its encoding in the XML declaration, but that does not guarantee a XML parser can handle it. Only UTF-8 and UTF-16 are mandatory, two variants of Unicode, a newer, enormous character architecture covering almost every imaginable symbol.
This section introduces Unicode with Perl and XML. You can use your traditional encoding for everything in this book, but may eventually find yourself swimming against the current.
Note: Character-set choices have advantages and drawbacks. Personally, I find the local German ISO 8859-1 easier for everyday work and chose it for these examples. It is not always sufficient—even neighboring Czech cannot be represented—so understanding Unicode is essential. —Translator’s note.
Unicode, Perl and XML
Unicode answers the digital needs of countless scripts that supported monks and linguists for centuries. If non-ASCII characters surround you, you may know it already. Unicode promotes this direction, Perl helps, and XML already relies on it.
Every Unicode advocate praises its usefulness for source-code internationalization. One character architecture adapts programs to almost any linguistic environment.
Unicode matters even more for data representation. A user’s language is only one aspect: computers touch everyone’s life, and some people speak Kurku. Understanding Unicode helps store arbitrary data independently of program architecture.
Unicode encoding systems
Distinguish architecture or character set from encoding: Unicode is an architecture with multiple encodings.
Every Unicode symbol, from A to α to ☺, has a code point, a unique positive integer locating it on the Unicode map. The first uppercase Latin letter has hexadecimal address 0x0041, as in ASCII and related sets. Greek alpha and the smiley have addresses 0x03B1 and 0x263A. Characters may use one code point or combinations. Some code points are diacritics, accents and radicals combined with letters or ideographs in many scripts.
These and tens of thousands, now perhaps hundreds of thousands, of other addresses are identical across Unicode encodings. Only their representation as low-level zeros and ones changes.
Unicode officially has three encoding systems, UTF (Unicode Transformation Format) followed by the minimum bits per character: UTF-8, UTF-16 and UTF-32. UTF-8 is most flexible and was adopted by Perl.
UTF-8
UTF-8 suits Perl by minimizing output bytes. Alone among these systems, it represents some characters with one byte. It is XML’s default: without an explicit encoding declaration, parsers should assume UTF-8.
Each UTF-8 character uses a number of bytes for its code point, up to six. A at 0x41 takes one byte. Our friend ☺ lives at 0x263A and needs three: two for the code point and one signaling three bytes total. In centuries, when Earth joins the Galactic Union of Friendship, Unicode may include alien scripts, putting bytes four to six to use.
UTF-16
UTF-16 always uses at least two bytes, even for addresses fitting in one, as UTF-8 might also do. Larger addresses may add two bytes, a surrogate pair, making four total.
Note: Unicode 2.0 knew only 16 bits per character. “Unicode” sometimes therefore means UTF-16: Save As dialogs may offer “Unicode” and “UTF-8”, not necessarily distinct in Unicode 3.2 terminology.
UTF-32
UTF-32 resembles UTF-16 without variable byte counts: every address takes four bytes. Documents grow large, with extra zeros reducing processing efficiency. XML parsers need not support it, so you probably need not worry further.
Other encodings
Besides the two mandatory encodings, XML defines 21 others that parsers should support, including ISO-8859-1, ASCII plus 128 Western European characters outside the Latin alphabet, and Shift_JIS, Microsoft’s Japanese encoding. Though not Unicode encodings, all their characters have Unicode code points.
Perl parsers handle other encodings differently, sometimes needing help. For instance, XML::Parser is weak because Expat supports few encodings. Fortunately, Clark Cooper’s module XML::Encoding solves this as a subclass of XML::Parser supporting map files. These XML maps associate Unicode code points with a character set’s symbols.
Perl core support
Perl’s romance with Unicode, like its romance with XML, developed slowly but inexorably.
Perhaps this seems too romantic, but Perl’s polygamous nature made it what it is.
Use Perl 5.8 or later for reasonable Unicode support. Consult perlunicode for your version’s support, since every release improves it.
Some tools here work with older Perl, but Perl XML work eventually means Unicode and exposes core limitations.
Perl 5.6 first offered partial Unicode support. The pragma use utf8 switches most string functions to UTF-8 and permits UTF-8 source, including local-letter identifiers, useful outside the Latin alphabet.
Nevertheless, avoid variable names such as
$länge; nothing is lost by writing$laenge.
Perl 5.8 goes further, including Unicode regular expressions and the built-in module Encode for easy character-set conversion:
use Encode 'from_to';
from_to($data, "iso-8859-1", "utf-8"); # vom lokalen Zeichensatz in UTF-8Perl 6 is being redesigned and rewritten around the community’s last 12 years of learning. It will rely more on Unicode, perhaps warranting another book edition. Keeping up is worthwhile.
Converting encodings
Before Perl 5.8, conversion needs help; our toolbox has suitable tools.
iconv and Text::Iconv
iconv is a library and program for Windows and Unix, including Mac OS X, converting documents from encoding A to B. From a Unix command line:
$ iconv -f latin1 -t utf8 my_file.txt > my_unicode_file.txt With iconv installed, add CPAN’s Text::Iconv module for a Perl interface converting in-memory strings.
Unicode::String
A more portable solution is the module Unicode::String, independent of external C libraries. Its interface is simple: pass a string to the constructor to obtain an object, then use methods to convert encodings or manipulate it in other entertaining ways. This example tests it.
Example: Testing Unicode::String
use Unicode::String;
my $string = "Diesen Satz gibt es in ASCII und UTF-8, aber nicht in UTF-16. Mist!\n";
my $u = Unicode::String->new($string);
# $u enthält nun ein Objekt, das einen String aus 16-Bit-Zeichen repräsentiert
# Dieses Objekt kennt Overloading, die Stringoperatoren funktionieren also wie erwartet!
$u .= "\n\nHey, auf einmal ist es Unicode. Hurra!!\n";
# Ausgabe in UTF-16 (auch als UCS2 bekannt)
print $u->ucs2;
# Ausgabe etwas lesefreundlicher
print $u->utf8; Methods also convert to simpler character sets, possibly losing unrepresentable characters. The method utf7 strips a UTF-8 character’s eighth bit, useful when sending ASCII to someone who would reach for a chainsaw at a non-ASCII character.
Warning!
XML::Parsersometimes seems obsessed with Unicode. Whatever the document’s declared encoding, higher code points silently become UTF-8; text retrieved from the parser is UTF-8. This can surprise you, soXML::Parsermay need these conversion tools.
Byte order
Unknown-source XML may have an unknown encoding. Inspecting its initial byte-order mark (BOM) can help. UTF-16 and UTF-32 depend on byte order; UTF-8 does not. Without knowing whether the most or least significant byte comes first, reading may resemble a mirror: everything reversed.
Unicode therefore defines the special code point U+FEFF as a byte-order mark. UTF-16 and UTF-32 documents may begin with it.
UTF-8 has its own mark, solely identifying the encoding, largely redundant in XML. UTF-8 uses byte sequences with a fixed order. In the 16- and 32-bit number sequences of UTF-8 and UTF-16, number order is fixed but byte order within each number is not.
A program first reads two bytes. Finding 0xFE and 0xFF selects big-endian UTF-16. Finding 0xFF 0xFE selects little-endian, since Unicode deliberately has no code point U+FFFE . UTF-32 marks are 0x00 0x00 0xFE 0xFF and 0xFF 0xFE 0x00 0x00, handled analogously.
XML requires BOMs in UTF-16 and UTF-32 documents. Unicode therefore implies network order for sensible, well-intentioned authors: big-endian, established long ago for machine communication. You too should follow network order unless certain otherwise. In doubt, this code may help:
open XML_FILE, $filename or die "Kann die Datei $filename nicht öffnen: $!";
my $bom; # Hier speichern wir eine evtl. Byte-Order-Markierung ab
# Lesen der ersten zwei Bytes
read XML_FILE, $bom, 2;
# Über die Perl-Funktion ord() erhalten wir die numerischen Werte
my $ord1 = ord(substr($bom,0,1));
my $ord2 = ord(substr($bom,1,1));
if ($ord1 == 0xFE && $ord2 == 0xFF) {
# Dies scheint ein Dokument in UTF-16, Big-Endian zu sein!
# ... wir verhalten uns entsprechend ...
} elsif ($ord1 == 0xFF && $ord2 == 0xEF) {
# Oh, jemand war so unfreundlich, ein Dokument in UTF-16 Little-Endian zu schicken.
# Wir müssen zum Beispiel die Bytes vertauschen.
} else {
# Keine Byte-Order-Markierung.
} Use this as an emergency measure if a parser cannot find XML. The first line may be a correct <?xml ... > declaration it simply fails to recognize.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Perl & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de