Yesterday a colleague passed me some code he had written saying it was not working properly but when he added 'use utf8' it worked. I asked him if his script was written in UTF-8 and he claimed it wasn't and indeed it was not. I could not immediately see why so reduced it to a few lines which demonstrate the problem. I can make it work but I cannot explain why. Any ideas?

#!/usr/bin/perl use strict; use warnings; use fred; my @line; format STDOUT_TOP = @<<<<<< @<<< @>>>>>>>>>>> "a", "b", "c" . format STDOUT = @<<<<<< @<<< @########.## @line . $line[0] = "\x{20ac}"; $line[1] = 'fre'; $line[2] = 2; write;
package fred; use encoding 'utf-8'; 1;
This produces:
a b c € fre < 2.00

He was not getting Wide character in print because he used the fred package and it contains an "encoding utf-8" which adds UTF-8 layer to STDOUT/STDIN. However, where does that '<' come from?

Strangely if you add "use encoding 'utf-8'" to the main script the '<' goes away but much more strange to me is that when he originally passed this to me he claimed adding 'use utf8' to the main script made the '<' go away. I thought all 'use utf8' did was allow you to write your Perl in UTF-8 and yet it appears to be changing the way this script works. Also, moving the 'encoding' down the script to anywhere after the format lines but before the write makes it return to printing '<'

Can anyone explain these strange results.


In reply to Strange unicode behaviour with UTF8 encoding and format by mje

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.