ข้อมูลจะ Unicode Wide Character เช่น
\u0e1e\u0e0d\u0e32\u0e44\u0e17 หรือ \u{E1E}\u{E0D}\u{E32}\u{E44}\u{E17}
ซึ่งจะหมายถึงคำว่า "พญาไท"
เมื่อใช้คำสั่ง decode_json($data) เราจะได้ผลลัพธ์เป็น Unicode Wide Character เสมอUnicode Wide Character
A character in the range 0 .. 2**32-1 (or more); what Perl's strings are made of.
Byte
A character in the range 0..255; a special case of a Perl character.
Octet
8 bits of data, with ordinal values 0..255; term for bytes passed to or from a non-Perl context,
such as a disk file, standard I/O stream, database, command-line argument, environment variable, etc.
Code: Select all
use JSON qw(decode_json);
$text = decode_json($data);
วิธีแก้คือต้องใช้
Code: Select all
binmode STDOUT, ':utf8';
หรือ
use open ':std', ':encoding(UTF-8)';
ดังนั้นก่อนที่เราจะใช้ฟังก์ชั่นพวก search, replace หรือ matching
จะต้องระบุ use utf8; เพื่อให้ Perl แปลงค่า Octet ให้เป็น Unicode Wide Character
แต่จะทำให้มีผลต่อ modules อื่นๆอีกตามมาด้วย
วิธีที่ดีที่สุดคือ ให้แปลงข้อมูล JSON จาก Unicode Wide Character ให้เป็น Octet เสียก่อน
และให้ยกเลิกการใช้ use utf8;
Internal functions
https://perldoc.perl.org/utf8.html
Code: Select all
utf8::encode($string); # "\x{100}" becomes "\xc4\x80"
utf8::decode($string); # "\xc4\x80" becomes "\x{100}"
https://perldoc.perl.org/Encode.html
Code: Select all
use Encode qw(encode decode);
$octets = encode('UTF-8', $characters);
$characters = decode('UTF-8', $octets);