Now that utf8 is routine, a couple of basic functions seem to be lagging behind a bit -- (s)printf won't work well at maintaining column alignment when you're working with Chinese/Japanese/Korean (CJK) strings, because the Asian characters are twice as wide as the spaces used to pad a "%s" field. Luckily, unicode (like the Asian character sets it replaces) has a set of "fullwidth" (double-wide) ASCII glyphs, so the fix is pretty easy.
package CJKprintf; require 5.008_000; use strict; use Exporter qw/import/; our @EXPORT = qw/CJKprintf CJKsprintf/; sub CJKprintf { print _normalize_width( @_ ); } sub CJKsprintf { _normalize_width( @_ ); } sub _normalize_width { my ( $format, @args ) = @_; my $string = sprintf( $format, @args ); $string =~ tr/ !-~/\x{3000}\x{ff01}-\x{ff5e}/; return $string; } =head1 NAME CJKprintf =head1 SYNOPSIS use CJKprintf; CJKprintf( "%5d %-8s\n", $number, $chinese_string ); $string = CJKsprintf( "%10s", $korean_string ); =head1 DESCRIPTION The functions "CJKprintf" and "CJKsprintf" are exported by default (and nothing else is exported). These functions can be used as replacements for the standard "printf/sprintf" whenever you need to maintain visual alignment of fixed-width fields when Asian character data is involved. This works by replacing all ASCII characters (space through tilde, \x20 - \x7E) with their "FULLWIDTH" (double-wide) unicode versions, so that these characters have the same display width as the CJK characters. As currently written, it does not "widen" any non-CJK (single-width) characters that lie outside the ASCII range. =cut

In reply to Asian text vs. (s)printf: CJKprintf by graff

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.