mje has asked for the wisdom of the Perl Monks concerning the following question:
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;
This produces:package fred; use encoding 'utf-8'; 1;
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Strange unicode behaviour with UTF8 encoding and format
by moritz (Cardinal) on Feb 18, 2010 at 09:55 UTC | |
by mje (Curate) on Feb 18, 2010 at 11:12 UTC |