การใช้งาน UTF-8 ใน Perl Programming Language

Post Reply
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

การใช้งาน UTF-8 ใน Perl Programming Language

Post by tong »

การดึงข้อมูลส่วนใหญ่จากเว็บเพจต่างๆ มักจะมาในรูปแบบของ JSON
ข้อมูลจะ Unicode Wide Character เช่น
\u0e1e\u0e0d\u0e32\u0e44\u0e17 หรือ \u{E1E}\u{E0D}\u{E32}\u{E44}\u{E17}
ซึ่งจะหมายถึงคำว่า "พญาไท"
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.
เมื่อใช้คำสั่ง decode_json($data) เราจะได้ผลลัพธ์เป็น Unicode Wide Character เสมอ

Code: Select all

use JSON qw(decode_json);
$text = decode_json($data);
เมื่อใช้คำสั่ง print ก็จะมีปัญหาเรื่อง Wide Character in print at XXX.pl line NN
วิธีแก้คือต้องใช้

Code: Select all

binmode STDOUT, ':utf8';
หรือ
use open ':std', ':encoding(UTF-8)';
ทีนี้โดยปกติเราจะเขียนโปรแกรมด้วย text editor ตัวอักษรไทยจะเป็นแบบ Octet
ดังนั้นก่อนที่เราจะใช้ฟังก์ชั่นพวก 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}"
Core modules Encode
https://perldoc.perl.org/Encode.html

Code: Select all

use Encode qw(encode decode);
$octets     = encode('UTF-8', $characters);
$characters = decode('UTF-8', $octets);
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: การใช้งาน UTF-8 ใน Perl Programming Language

Post by tong »

ความแตกต่างระหว่าง utf8 และ UTF-8

utf8 เป็นแบบเดิม เสรีนิยม และหละหลวม
UTF-8 เป็นแบบใหม่ อนุรักษ์นิยม เข้มงวด และมีความปลอดภัย

Code: Select all

find_encoding("UTF-8")->name # is 'utf-8-strict'
find_encoding("utf-8")->name # ditto. names are case insensitive
find_encoding("utf_8")->name # ditto. "_" are treated as "-"
find_encoding("UTF8")->name  # is 'utf8'
Post Reply