The iso-latin-1 character set is much smaller than the Unicode character set. Fortunately, HTML provides a mechanism to encode character not present in the used character set.

Option 1 (Works with any encoding):

my $to_entitise = q{<>&"'}; # Unsafe for HTML my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html, Encode::FB_HTML +CREF);

Option 2 (Leverages our knowledge of iso-latin-1):

my $to_entitise = q{<>&"'} . # Unsafe for HTML q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);

Option 3 (Works with any encoding by using HTML entities for more than needed):

my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text); my $latin1_html = encode('iso-latin-1', $decoded_html);

If your UTF-8 encoded data is HTML rather than text, you can use:

my $to_entitise = q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_html = decode('UTF-8', $utf8_html); $decoded_html = encode_entities($decoded_html, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);

Common headers and test data:

use charnames qw( :full ); # For \N on older Perls use Encode qw( encode decode ); use HTML::Entities qw( encode_entities ); my $utf8_text = encode('UTF-8', "a\N{U+00E9}\N{U+2660} 1<4"); my $utf8_html = encode('UTF-8', "a\N{U+00E9}\N{U+2660} <b>foo</b>");

Update: Small fixes to bugs found during testing.


In reply to Re: Converting UTF8 to Latin1 by ikegami
in thread Converting UTF8 to Latin1 by sumeetgrover

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.