Perl 5 version documentation

perlunicook

NAME

perlunicook - cookbookish examples of handling Unicode in Perl

DESCRIPTION

This manpage contains short recipes demonstrating how to handle common Unicode operations in Perl, plus one complete program at the end. Any undeclared variables in individual recipes are assumed to have a previous appropriate value in them.

EXAMPLES

℞ 0: Standard preamble

Unless otherwise notes, all examples below require this standard preamble to work correctly, with the #! adjusted to work on your system:

  1. #!/usr/bin/env perl
  2. use utf8; # so literals and identifiers can be in UTF-8
  3. use v5.12; # or later to get "unicode_strings" feature
  4. use strict; # quote strings, declare variables
  5. use warnings; # on by default
  6. use warnings qw(FATAL utf8); # fatalize encoding glitches
  7. use open qw(:std :encoding(UTF-8)); # undeclared streams in UTF-8
  8. use charnames qw(:full :short); # unneeded in v5.16

This does make even Unix programmers binmode your binary streams, or open them with :raw , but that's the only way to get at them portably anyway.

WARNING: use autodie (pre 2.26) and use open do not get along with each other.

℞ 1: Generic Unicode-savvy filter

Always decompose on the way in, then recompose on the way out.

  1. use Unicode::Normalize;
  2. while (<>) {
  3. $_ = NFD($_); # decompose + reorder canonically
  4. ...
  5. } continue {
  6. print NFC($_); # recompose (where possible) + reorder canonically
  7. }

℞ 2: Fine-tuning Unicode warnings

As of v5.14, Perl distinguishes three subclasses of UTF‑8 warnings.

  1. use v5.14; # subwarnings unavailable any earlier
  2. no warnings "nonchar"; # the 66 forbidden non-characters
  3. no warnings "surrogate"; # UTF-16/CESU-8 nonsense
  4. no warnings "non_unicode"; # for codepoints over 0x10_FFFF

℞ 3: Declare source in utf8 for identifiers and literals

Without the all-critical use utf8 declaration, putting UTF‑8 in your literals and identifiers won’t work right. If you used the standard preamble just given above, this already happened. If you did, you can do things like this:

  1. use utf8;
  2. my $measure = "Ångström";
  3. my @μsoft = qw( cp852 cp1251 cp1252 );
  4. my @ὑπέρμεγας = qw( ὑπέρ μεγας );
  5. my @鯉 = qw( koi8-f koi8-u koi8-r );
  6. my $motto = "👪 💗 🐪"; # FAMILY, GROWING HEART, DROMEDARY CAMEL

If you forget use utf8 , high bytes will be misunderstood as separate characters, and nothing will work right.

℞ 4: Characters and their numbers

The ord and chr functions work transparently on all codepoints, not just on ASCII alone — nor in fact, not even just on Unicode alone.

  1. # ASCII characters
  2. ord("A")
  3. chr(65)
  4. # characters from the Basic Multilingual Plane
  5. ord("Σ")
  6. chr(0x3A3)
  7. # beyond the BMP
  8. ord("𝑛") # MATHEMATICAL ITALIC SMALL N
  9. chr(0x1D45B)
  10. # beyond Unicode! (up to MAXINT)
  11. ord("\x{20_0000}")
  12. chr(0x20_0000)

℞ 5: Unicode literals by character number

In an interpolated literal, whether a double-quoted string or a regex, you may specify a character by its number using the \x{HHHHHH} escape.

  1. String: "\x{3a3}"
  2. Regex: /\x{3a3}/
  3. String: "\x{1d45b}"
  4. Regex: /\x{1d45b}/
  5. # even non-BMP ranges in regex work fine
  6. /[\x{1D434}-\x{1D467}]/

℞ 6: Get character name by number

  1. use charnames ();
  2. my $name = charnames::viacode(0x03A3);

℞ 7: Get character number by name

  1. use charnames ();
  2. my $number = charnames::vianame("GREEK CAPITAL LETTER SIGMA");

℞ 8: Unicode named characters

Use the \N{charname} notation to get the character by that name for use in interpolated literals (double-quoted strings and regexes). In v5.16, there is an implicit

  1. use charnames qw(:full :short);

But prior to v5.16, you must be explicit about which set of charnames you want. The :full names are the official Unicode character name, alias, or sequence, which all share a namespace.

  1. use charnames qw(:full :short latin greek);
  2. "\N{MATHEMATICAL ITALIC SMALL N}" # :full
  3. "\N{GREEK CAPITAL LETTER SIGMA}" # :full

Anything else is a Perl-specific convenience abbreviation. Specify one or more scripts by names if you want short names that are script-specific.

  1. "\N{Greek:Sigma}" # :short
  2. "\N{ae}" # latin
  3. "\N{epsilon}" # greek

The v5.16 release also supports a :loose import for loose matching of character names, which works just like loose matching of property names: that is, it disregards case, whitespace, and underscores:

  1. "\N{euro sign}" # :loose (from v5.16)

℞ 9: Unicode named sequences

These look just like character names but return multiple codepoints. Notice the %vx vector-print functionality in printf.

  1. use charnames qw(:full);
  2. my $seq = "\N{LATIN CAPITAL LETTER A WITH MACRON AND GRAVE}";
  3. printf "U+%v04X\n", $seq;
  4. U+0100.0300

℞ 10: Custom named characters

Use :alias to give your own lexically scoped nicknames to existing characters, or even to give unnamed private-use characters useful names.

  1. use charnames ":full", ":alias" => {
  2. ecute => "LATIN SMALL LETTER E WITH ACUTE",
  3. "APPLE LOGO" => 0xF8FF, # private use character
  4. };
  5. "\N{ecute}"
  6. "\N{APPLE LOGO}"

℞ 11: Names of CJK codepoints

Sinograms like “東京” come back with character names of CJK UNIFIED IDEOGRAPH-6771 and CJK UNIFIED IDEOGRAPH-4EAC, because their “names” vary. The CPAN Unicode::Unihan module has a large database for decoding these (and a whole lot more), provided you know how to understand its output.

  1. # cpan -i Unicode::Unihan
  2. use Unicode::Unihan;
  3. my $str = "東京";
  4. my $unhan = Unicode::Unihan->new;
  5. for my $lang (qw(Mandarin Cantonese Korean JapaneseOn JapaneseKun)) {
  6. printf "CJK $str in %-12s is ", $lang;
  7. say $unhan->$lang($str);
  8. }

prints:

  1. CJK 東京 in Mandarin is DONG1JING1
  2. CJK 東京 in Cantonese is dung1ging1
  3. CJK 東京 in Korean is TONGKYENG
  4. CJK 東京 in JapaneseOn is TOUKYOU KEI KIN
  5. CJK 東京 in JapaneseKun is HIGASHI AZUMAMIYAKO

If you have a specific romanization scheme in mind, use the specific module:

  1. # cpan -i Lingua::JA::Romanize::Japanese
  2. use Lingua::JA::Romanize::Japanese;
  3. my $k2r = Lingua::JA::Romanize::Japanese->new;
  4. my $str = "東京";
  5. say "Japanese for $str is ", $k2r->chars($str);

prints

  1. Japanese for 東京 is toukyou

℞ 12: Explicit encode/decode

On rare occasion, such as a database read, you may be given encoded text you need to decode.

  1. use Encode qw(encode decode);
  2. my $chars = decode("shiftjis", $bytes, 1);
  3. # OR
  4. my $bytes = encode("MIME-Header-ISO_2022_JP", $chars, 1);

For streams all in the same encoding, don't use encode/decode; instead set the file encoding when you open the file or immediately after with binmode as described later below.

℞ 13: Decode program arguments as utf8

  1. $ perl -CA ...
  2. or
  3. $ export PERL_UNICODE=A
  4. or
  5. use Encode qw(decode);
  6. @ARGV = map { decode('UTF-8', $_, 1) } @ARGV;

℞ 14: Decode program arguments as locale encoding

  1. # cpan -i Encode::Locale
  2. use Encode qw(locale);
  3. use Encode::Locale;
  4. # use "locale" as an arg to encode/decode
  5. @ARGV = map { decode(locale => $_, 1) } @ARGV;

℞ 15: Declare STD{IN,OUT,ERR} to be utf8

Use a command-line option, an environment variable, or else call binmode explicitly:

  1. $ perl -CS ...
  2. or
  3. $ export PERL_UNICODE=S
  4. or
  5. use open qw(:std :encoding(UTF-8));
  6. or
  7. binmode(STDIN, ":encoding(UTF-8)");
  8. binmode(STDOUT, ":utf8");
  9. binmode(STDERR, ":utf8");

℞ 16: Declare STD{IN,OUT,ERR} to be in locale encoding

  1. # cpan -i Encode::Locale
  2. use Encode;
  3. use Encode::Locale;
  4. # or as a stream for binmode or open
  5. binmode STDIN, ":encoding(console_in)" if -t STDIN;
  6. binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
  7. binmode STDERR, ":encoding(console_out)" if -t STDERR;

℞ 17: Make file I/O default to utf8

Files opened without an encoding argument will be in UTF-8:

  1. $ perl -CD ...
  2. or
  3. $ export PERL_UNICODE=D
  4. or
  5. use open qw(:encoding(UTF-8));

℞ 18: Make all I/O and args default to utf8

  1. $ perl -CSDA ...
  2. or
  3. $ export PERL_UNICODE=SDA
  4. or
  5. use open qw(:std :encoding(UTF-8));
  6. use Encode qw(decode);
  7. @ARGV = map { decode('UTF-8', $_, 1) } @ARGV;

℞ 19: Open file with specific encoding

Specify stream encoding. This is the normal way to deal with encoded text, not by calling low-level functions.

  1. # input file
  2. open(my $in_file, "< :encoding(UTF-16)", "wintext");
  3. OR
  4. open(my $in_file, "<", "wintext");
  5. binmode($in_file, ":encoding(UTF-16)");
  6. THEN
  7. my $line = <$in_file>;
  8. # output file
  9. open($out_file, "> :encoding(cp1252)", "wintext");
  10. OR
  11. open(my $out_file, ">", "wintext");
  12. binmode($out_file, ":encoding(cp1252)");
  13. THEN
  14. print $out_file "some text\n";

More layers than just the encoding can be specified here. For example, the incantation ":raw :encoding(UTF-16LE) :crlf" includes implicit CRLF handling.

℞ 20: Unicode casing

Unicode casing is very different from ASCII casing.

  1. uc("henry ⅷ") # "HENRY Ⅷ"
  2. uc("tschüß") # "TSCHÜSS" notice ß => SS
  3. # both are true:
  4. "tschüß" =~ /TSCHÜSS/i # notice ß => SS
  5. "Σίσυφος" =~ /ΣΊΣΥΦΟΣ/i # notice Σ,σ,ς sameness

℞ 21: Unicode case-insensitive comparisons

Also available in the CPAN Unicode::CaseFold module, the new fc “foldcase” function from v5.16 grants access to the same Unicode casefolding as the /i pattern modifier has always used:

  1. use feature "fc"; # fc() function is from v5.16
  2. # sort case-insensitively
  3. my @sorted = sort { fc($a) cmp fc($b) } @list;
  4. # both are true:
  5. fc("tschüß") eq fc("TSCHÜSS")
  6. fc("Σίσυφος") eq fc("ΣΊΣΥΦΟΣ")

℞ 22: Match Unicode linebreak sequence in regex

A Unicode linebreak matches the two-character CRLF grapheme or any of seven vertical whitespace characters. Good for dealing with textfiles coming from different operating systems.

  1. \R
  2. s/\R/\n/g; # normalize all linebreaks to \n

℞ 23: Get character category

Find the general category of a numeric codepoint.

  1. use Unicode::UCD qw(charinfo);
  2. my $cat = charinfo(0x3A3)->{category}; # "Lu"

℞ 24: Disabling Unicode-awareness in builtin charclasses

Disable \w , \b , \s, \d , and the POSIX classes from working correctly on Unicode either in this scope, or in just one regex.

  1. use v5.14;
  2. use re "/a";
  3. # OR
  4. my($num) = $str =~ /(\d+)/a;

Or use specific un-Unicode properties, like \p{ahex} and \p{POSIX_Digit}. Properties still work normally no matter what charset modifiers (/d /u /l /a /aa ) should be effect.

℞ 25: Match Unicode properties in regex with \p, \P

These all match a single codepoint with the given property. Use \P in place of \p to match one codepoint lacking that property.

  1. \pL, \pN, \pS, \pP, \pM, \pZ, \pC
  2. \p{Sk}, \p{Ps}, \p{Lt}
  3. \p{alpha}, \p{upper}, \p{lower}
  4. \p{Latin}, \p{Greek}
  5. \p{script_extensions=Latin}, \p{scx=Greek}
  6. \p{East_Asian_Width=Wide}, \p{EA=W}
  7. \p{Line_Break=Hyphen}, \p{LB=HY}
  8. \p{Numeric_Value=4}, \p{NV=4}

℞ 26: Custom character properties

Define at compile-time your own custom character properties for use in regexes.

  1. # using private-use characters
  2. sub In_Tengwar { "E000\tE07F\n" }
  3. if (/\p{In_Tengwar}/) { ... }
  4. # blending existing properties
  5. sub Is_GraecoRoman_Title {<<'END_OF_SET'}
  6. +utf8::IsLatin
  7. +utf8::IsGreek
  8. &utf8::IsTitle
  9. END_OF_SET
  10. if (/\p{Is_GraecoRoman_Title}/ { ... }

℞ 27: Unicode normalization

Typically render into NFD on input and NFC on output. Using NFKC or NFKD functions improves recall on searches, assuming you've already done to the same text to be searched. Note that this is about much more than just pre- combined compatibility glyphs; it also reorders marks according to their canonical combining classes and weeds out singletons.

  1. use Unicode::Normalize;
  2. my $nfd = NFD($orig);
  3. my $nfc = NFC($orig);
  4. my $nfkd = NFKD($orig);
  5. my $nfkc = NFKC($orig);

℞ 28: Convert non-ASCII Unicode numerics

Unless you’ve used /a or /aa, \d matches more than ASCII digits only, but Perl’s implicit string-to-number conversion does not current recognize these. Here’s how to convert such strings manually.

  1. use v5.14; # needed for num() function
  2. use Unicode::UCD qw(num);
  3. my $str = "got Ⅻ and ४५६७ and ⅞ and here";
  4. my @nums = ();
  5. while ($str =~ /(\d+|\N)/g) { # not just ASCII!
  6. push @nums, num($1);
  7. }
  8. say "@nums"; # 12 4567 0.875
  9. use charnames qw(:full);
  10. my $nv = num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");

℞ 29: Match Unicode grapheme cluster in regex

Programmer-visible “characters” are codepoints matched by /./s , but user-visible “characters” are graphemes matched by /\X/ .

  1. # Find vowel *plus* any combining diacritics,underlining,etc.
  2. my $nfd = NFD($orig);
  3. $nfd =~ / (?=[aeiou]) \X /xi

℞ 30: Extract by grapheme instead of by codepoint (regex)

  1. # match and grab five first graphemes
  2. my($first_five) = $str =~ /^ ( \X{5} ) /x;

℞ 31: Extract by grapheme instead of by codepoint (substr)

  1. # cpan -i Unicode::GCString
  2. use Unicode::GCString;
  3. my $gcs = Unicode::GCString->new($str);
  4. my $first_five = $gcs->substr(0, 5);

℞ 32: Reverse string by grapheme

Reversing by codepoint messes up diacritics, mistakenly converting crème brûlée into éel̂urb em̀erc instead of into eélûrb emèrc ; so reverse by grapheme instead. Both these approaches work right no matter what normalization the string is in:

  1. $str = join("", reverse $str =~ /\X/g);
  2. # OR: cpan -i Unicode::GCString
  3. use Unicode::GCString;
  4. $str = reverse Unicode::GCString->new($str);

℞ 33: String length in graphemes

The string brûlée has six graphemes but up to eight codepoints. This counts by grapheme, not by codepoint:

  1. my $str = "brûlée";
  2. my $count = 0;
  3. while ($str =~ /\X/g) { $count++ }
  4. # OR: cpan -i Unicode::GCString
  5. use Unicode::GCString;
  6. my $gcs = Unicode::GCString->new($str);
  7. my $count = $gcs->length;

℞ 34: Unicode column-width for printing

Perl’s printf, sprintf, and format think all codepoints take up 1 print column, but many take 0 or 2. Here to show that normalization makes no difference, we print out both forms:

  1. use Unicode::GCString;
  2. use Unicode::Normalize;
  3. my @words = qw/crème brûlée/;
  4. @words = map { NFC($_), NFD($_) } @words;
  5. for my $str (@words) {
  6. my $gcs = Unicode::GCString->new($str);
  7. my $cols = $gcs->columns;
  8. my $pad = " " x (10 - $cols);
  9. say str, $pad, " |";
  10. }

generates this to show that it pads correctly no matter the normalization:

  1. crème |
  2. crème |
  3. brûlée |
  4. brûlée |

℞ 35: Unicode collation

Text sorted by numeric codepoint follows no reasonable alphabetic order; use the UCA for sorting text.

  1. use Unicode::Collate;
  2. my $col = Unicode::Collate->new();
  3. my @list = $col->sort(@old_list);

See the ucsort program from the Unicode::Tussle CPAN module for a convenient command-line interface to this module.

℞ 36: Case- and accent-insensitive Unicode sort

Specify a collation strength of level 1 to ignore case and diacritics, only looking at the basic character.

  1. use Unicode::Collate;
  2. my $col = Unicode::Collate->new(level => 1);
  3. my @list = $col->sort(@old_list);

℞ 37: Unicode locale collation

Some locales have special sorting rules.

  1. # either use v5.12, OR: cpan -i Unicode::Collate::Locale
  2. use Unicode::Collate::Locale;
  3. my $col = Unicode::Collate::Locale->new(locale => "de__phonebook");
  4. my @list = $col->sort(@old_list);

The ucsort program mentioned above accepts a --locale parameter.

℞ 38: Making cmp work on text instead of codepoints

Instead of this:

  1. @srecs = sort {
  2. $b->{AGE} <=> $a->{AGE}
  3. ||
  4. $a->{NAME} cmp $b->{NAME}
  5. } @recs;

Use this:

  1. my $coll = Unicode::Collate->new();
  2. for my $rec (@recs) {
  3. $rec->{NAME_key} = $coll->getSortKey( $rec->{NAME} );
  4. }
  5. @srecs = sort {
  6. $b->{AGE} <=> $a->{AGE}
  7. ||
  8. $a->{NAME_key} cmp $b->{NAME_key}
  9. } @recs;

℞ 39: Case- and accent-insensitive comparisons

Use a collator object to compare Unicode text by character instead of by codepoint.

  1. use Unicode::Collate;
  2. my $es = Unicode::Collate->new(
  3. level => 1,
  4. normalization => undef
  5. );
  6. # now both are true:
  7. $es->eq("García", "GARCIA" );
  8. $es->eq("Márquez", "MARQUEZ");

℞ 40: Case- and accent-insensitive locale comparisons

Same, but in a specific locale.

  1. my $de = Unicode::Collate::Locale->new(
  2. locale => "de__phonebook",
  3. );
  4. # now this is true:
  5. $de->eq("tschüß", "TSCHUESS"); # notice ü => UE, ß => SS

℞ 41: Unicode linebreaking

Break up text into lines according to Unicode rules.

  1. # cpan -i Unicode::LineBreak
  2. use Unicode::LineBreak;
  3. use charnames qw(:full);
  4. my $para = "This is a super\N{HYPHEN}long string. " x 20;
  5. my $fmt = Unicode::LineBreak->new;
  6. print $fmt->break($para), "\n";

℞ 42: Unicode text in DBM hashes, the tedious way

Using a regular Perl string as a key or value for a DBM hash will trigger a wide character exception if any codepoints won’t fit into a byte. Here’s how to manually manage the translation:

  1. use DB_File;
  2. use Encode qw(encode decode);
  3. tie %dbhash, "DB_File", "pathname";
  4. # STORE
  5. # assume $uni_key and $uni_value are abstract Unicode strings
  6. my $enc_key = encode("UTF-8", $uni_key, 1);
  7. my $enc_value = encode("UTF-8", $uni_value, 1);
  8. $dbhash{$enc_key} = $enc_value;
  9. # FETCH
  10. # assume $uni_key holds a normal Perl string (abstract Unicode)
  11. my $enc_key = encode("UTF-8", $uni_key, 1);
  12. my $enc_value = $dbhash{$enc_key};
  13. my $uni_value = decode("UTF-8", $enc_value, 1);

℞ 43: Unicode text in DBM hashes, the easy way

Here’s how to implicitly manage the translation; all encoding and decoding is done automatically, just as with streams that have a particular encoding attached to them:

  1. use DB_File;
  2. use DBM_Filter;
  3. my $dbobj = tie %dbhash, "DB_File", "pathname";
  4. $dbobj->Filter_Value("utf8"); # this is the magic bit
  5. # STORE
  6. # assume $uni_key and $uni_value are abstract Unicode strings
  7. $dbhash{$uni_key} = $uni_value;
  8. # FETCH
  9. # $uni_key holds a normal Perl string (abstract Unicode)
  10. my $uni_value = $dbhash{$uni_key};

℞ 44: PROGRAM: Demo of Unicode collation and printing

Here’s a full program showing how to make use of locale-sensitive sorting, Unicode casing, and managing print widths when some of the characters take up zero or two columns, not just one column each time. When run, the following program produces this nicely aligned output:

  1. Crème Brûlée....... €2.00
  2. Éclair............. €1.60
  3. Fideuà............. €4.20
  4. Hamburger.......... €6.00
  5. Jamón Serrano...... €4.45
  6. Linguiça........... €7.00
  7. Pâté............... €4.15
  8. Pears.............. €2.00
  9. Pêches............. €2.25
  10. Smørbrød........... €5.75
  11. Spätzle............ €5.50
  12. Xoriço............. €3.00
  13. Γύρος.............. €6.50
  14. 막걸리............. €4.00
  15. おもち............. €2.65
  16. お好み焼き......... €8.00
  17. シュークリーム..... €1.85
  18. 寿司............... €9.99
  19. 包子............... €7.50

Here's that program; tested on v5.14.

  1. #!/usr/bin/env perl
  2. # umenu - demo sorting and printing of Unicode food
  3. #
  4. # (obligatory and increasingly long preamble)
  5. #
  6. use utf8;
  7. use v5.14; # for locale sorting
  8. use strict;
  9. use warnings;
  10. use warnings qw(FATAL utf8); # fatalize encoding faults
  11. use open qw(:std :encoding(UTF-8)); # undeclared streams in UTF-8
  12. use charnames qw(:full :short); # unneeded in v5.16
  13. # std modules
  14. use Unicode::Normalize; # std perl distro as of v5.8
  15. use List::Util qw(max); # std perl distro as of v5.10
  16. use Unicode::Collate::Locale; # std perl distro as of v5.14
  17. # cpan modules
  18. use Unicode::GCString; # from CPAN
  19. # forward defs
  20. sub pad($$$);
  21. sub colwidth(_);
  22. sub entitle(_);
  23. my %price = (
  24. "γύρος" => 6.50, # gyros
  25. "pears" => 2.00, # like um, pears
  26. "linguiça" => 7.00, # spicy sausage, Portuguese
  27. "xoriço" => 3.00, # chorizo sausage, Catalan
  28. "hamburger" => 6.00, # burgermeister meisterburger
  29. "éclair" => 1.60, # dessert, French
  30. "smørbrød" => 5.75, # sandwiches, Norwegian
  31. "spätzle" => 5.50, # Bayerisch noodles, little sparrows
  32. "包子" => 7.50, # bao1 zi5, steamed pork buns, Mandarin
  33. "jamón serrano" => 4.45, # country ham, Spanish
  34. "pêches" => 2.25, # peaches, French
  35. "シュークリーム" => 1.85, # cream-filled pastry like eclair
  36. "막걸리" => 4.00, # makgeolli, Korean rice wine
  37. "寿司" => 9.99, # sushi, Japanese
  38. "おもち" => 2.65, # omochi, rice cakes, Japanese
  39. "crème brûlée" => 2.00, # crema catalana
  40. "fideuà" => 4.20, # more noodles, Valencian
  41. # (Catalan=fideuada)
  42. "pâté" => 4.15, # gooseliver paste, French
  43. "お好み焼き" => 8.00, # okonomiyaki, Japanese
  44. );
  45. my $width = 5 + max map { colwidth } keys %price;
  46. # So the Asian stuff comes out in an order that someone
  47. # who reads those scripts won't freak out over; the
  48. # CJK stuff will be in JIS X 0208 order that way.
  49. my $coll = Unicode::Collate::Locale->new(locale => "ja");
  50. for my $item ($coll->sort(keys %price)) {
  51. print pad(entitle($item), $width, ".");
  52. printf " €%.2f\n", $price{$item};
  53. }
  54. sub pad($$$) {
  55. my($str, $width, $padchar) = @_;
  56. return $str . ($padchar x ($width - colwidth($str)));
  57. }
  58. sub colwidth(_) {
  59. my($str) = @_;
  60. return Unicode::GCString->new($str)->columns;
  61. }
  62. sub entitle(_) {
  63. my($str) = @_;
  64. $str =~ s{ (?=\pL)(\S) (\S*) }
  65. { ucfirst($1) . lc($2) }xge;
  66. return $str;
  67. }

SEE ALSO

See these manpages, some of which are CPAN modules: perlunicode, perluniprops, perlre, perlrecharclass, perluniintro, perlunitut, perlunifaq, PerlIO, DB_File, DBM_Filter, DBM_Filter::utf8, Encode, Encode::Locale, Unicode::UCD, Unicode::Normalize, Unicode::GCString, Unicode::LineBreak, Unicode::Collate, Unicode::Collate::Locale, Unicode::Unihan, Unicode::CaseFold, Unicode::Tussle, Lingua::JA::Romanize::Japanese, Lingua::ZH::Romanize::Pinyin, Lingua::KO::Romanize::Hangul.

The Unicode::Tussle CPAN module includes many programs to help with working with Unicode, including these programs to fully or partly replace standard utilities: tcgrep instead of egrep, uniquote instead of cat -v or hexdump, uniwc instead of wc, unilook instead of look, unifmt instead of fmt, and ucsort instead of sort. For exploring Unicode character names and character properties, see its uniprops, unichars, and uninames programs. It also supplies these programs, all of which are general filters that do Unicode-y things: unititle and unicaps; uniwide and uninarrow; unisupers and unisubs; nfd, nfc, nfkd, and nfkc; and uc, lc, and tc.

Finally, see the published Unicode Standard (page numbers are from version 6.0.0), including these specific annexes and technical reports:

  • §3.13 Default Case Algorithms, page 113; §4.2 Case, pages 120–122; Case Mappings, page 166–172, especially Caseless Matching starting on page 170.
  • UAX #44: Unicode Character Database
  • UTS #18: Unicode Regular Expressions
  • UAX #15: Unicode Normalization Forms
  • UTS #10: Unicode Collation Algorithm
  • UAX #29: Unicode Text Segmentation
  • UAX #14: Unicode Line Breaking Algorithm
  • UAX #11: East Asian Width

AUTHOR

Tom Christiansen <tchrist@perl.com> wrote this, with occasional kibbitzing from Larry Wall and Jeffrey Friedl in the background.

COPYRIGHT AND LICENCE

Copyright © 2012 Tom Christiansen.

This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.

Most of these examples taken from the current edition of the “Camel Book”; that is, from the 4ᵗʰ Edition of Programming Perl, Copyright © 2012 Tom Christiansen <et al.>, 2012-02-13 by O’Reilly Media. The code itself is freely redistributable, and you are encouraged to transplant, fold, spindle, and mutilate any of the examples in this manpage however you please for inclusion into your own programs without any encumbrance whatsoever. Acknowledgement via code comment is polite but not required.

REVISION HISTORY

v1.0.0 – first public release, 2012-02-27