æ¥æ¬èªã®æ±ã | Mojoliciouså ¥é
ãMojoliciousã«ãããæ¥æ¬èªã®æ±ãã«ã¤ãã¦è§£èª¬ãã¦ããã¾ããPerlã使ãå ´åã«ãå¦ç¿ããã®ãé£ããæããã®ã¯ãæåã³ã¼ãã®æ±ãã§ããããPerlã§ã®æåã³ã¼ãã®æ±ãèªä½ã¯ãããã¦ç°¡åãªã®ã§ãããç¾ä»£çãªæ¹æ³ãç¥ããªãã¨ããçç±ã§æ··ä¹±ããã¦ããæ¹ãå¤ãã¨æãã¾ãã
ãéå»ã®æ´å²ãçè«ã¯ããã¦ããã¦ãããã§ã¯å®ç¨çãªé ç®ã«çµã£ã¦çµã£ã¦è§£èª¬ãã¾ãã詳ãã解説ã«ã¤ãã¦ã¯ãEncode - 日本語などのマルチバイト文字列を適切に処理する / Perlモジュール徹底解説ããåèã«ãã¦ãã ããã
ãã¤ãæååã¨å é¨æåå
ãPerlã§ã¯ãããã°ã©ã ã®å é¨ã§ã¯å é¨æååã使ã£ã¦ãããã°ã©ã ã®å¤é¨ã«å¯¾ãã¦ã¯ãç¹å®ã®æåã³ã¼ãã§è¡¨ç¾ããããã¤ãæååãå ¥åã¨ãã¦åãåã£ãããåºåããããã¾ãã
ãããã°ã©ã ã®å é¨ã§ã¯å é¨æååãããã°ã©ã ã®å¤é¨ã§ã¯ãã¤ãæååã¨èãã¦ãã ããã
ããã°ã©ã ã®å é¨ - å é¨æåå ããã°ã©ã ã®å¤é¨ - ãã¤ãæåå
ãJavaãç¥ã£ã¦ããã®ã§ããã°ãåç´ã«æååã¹ããªã¼ã ã¨ãã¤ãã¹ããªã¼ã ã ã¨èãã¦ã¿ã¦ãã ããã
ãã¤ã¾ãPerlã§ã¯ãå é¨æååã¨ãã¤ãæååã®å¤æãå¿ è¦ã ã¨ãããã¨ã§ãããã®å¤æãè¡ãã¢ã¸ã¥ã¼ã«ããEncodeã¢ã¸ã¥ã¼ã«ã§ãã
use Encode qw/encode decode/; # ãã³ã¼ã(ç¹å®ã®æåã³ã¼ãã§è¡¨ç¾ããããã¤ãæååãå é¨æååã«å¤æ) my $str_internal = decode('UTF-8', $str_byte); # ã¨ã³ã³ã¼ã(å é¨æååãç¹å®ã®æåã³ã¼ãã§è¡¨ç¾ããããã¤ãæååã«å¤æ) my $str_byte = encode('UTF-6', $str_internal);
ãEncodeã¢ã¸ã¥ã¼ã«ã®encodeé¢æ°ã¨decodeé¢æ°ã使ã£ã¦ãå é¨æååã¨ãã¤ãæååã®å¤æãè¡ãã¾ãã
utf8ãã©ã°ã
ã次ã«ããã²ã¨ã¤utf8ãã©ã°ãã®å©ç¨æ¹æ³ãè¦ã¦ããã¾ããããã½ã¼ã¹ã³ã¼ããUTF-8ã§ä¿åãããå ´åã¯ãã½ã¼ã¹ã³ã¼ãã®ä¸ã®æååã¯ãUTF-8ãã¤ãæååã§ãã
# UTF-8ãã¤ãæåå my $str_byte = 'ããããã';
ãutf8ãã©ã°ããæå¹ã«ããã¨ãã½ã¼ã¹ã³ã¼ãã®ä¸ã®æååã¯ãå é¨æååã¨ãã¦è§£éããã¾ãã
# å é¨æåå my $str_internal = 'ãããããã';
ãPerlã§ã½ã¼ã¹ã³ã¼ãã®ä¸ã§æ¥æ¬èªãæ±ãå ´åã¯ãå¿ ãutf8ãæå¹ã«ãã¦ãã½ã¼ã¹ã³ã¼ããUTF-8ã§ä¿åããããã«ãã¦ãã ããã
Mojoliciousã«ãããæ¥æ¬èªã®æ±ã
ãMojoliciousã¨ãããã¬ã¼ã ã¯ã¼ã¯ãããã®ç¾ä»£çãªPerlã®æååã®æ±ãã¨ã¾ã£ããåãèãæ¹ã«ãªã£ã¦ãã¾ãããã¤ãããããã¹ã¦ãèªåçã«è¡ã£ã¦ãããã®ã§é常ã«æ¥½ã§ããåæã¨ãã¦ã½ã¼ã¹ã³ã¼ãã¨ãã³ãã¬ã¼ãã¯UTF-8ã§å¿ ãä¿åãã¾ãããã
ãMojoliciousã¨ãããã¬ã¼ã ã¯ã¼ã¯ã¯ã以ä¸ã®æ©è½ãæä¾ãã¾ãã
- utf8ãã©ã°ãã¯èªåçã«æå¹ã«ãªãã¾ãã
- ãã³ãã¬ã¼ãã«æç»ããã¨ãã¯å é¨æååãUTF-8ãã¤ãæååã«èªåçã«å¤æããã¾ã
- ãã©ã¼ã ããåãåãã¨ãã¯UTF-8ãã¤ãæååãå é¨æååã«èªåçã«å¤æããã¾ã
ãã²ã¨ã¤ã¥ã¤è§£èª¬ãã¾ãã
utf8ãã©ã°ãã¯èªåçã«æå¹ã«ãªã
ãMojoliciousã§ã¯ãMojo::Baseã¨ããã¯ã©ã¹ãç¶æ¿ãã¦ããã¯ã©ã¹ã¯ãutf8ãã©ã°ããèªåçã«æå¹ã«ãªãã¾ããMojoliciousã®æ©è½ã使ãã¨ãã¯ãå¿ ãMojo::Baseãç¶æ¿ãã¦ããã¯ã©ã¹ã使ããã¨ã«ãªãã®ã§ããã¹ã¦ã®ã¯ã©ã¹ã¨ãã³ãã¬ã¼ãã§utf8ãã©ã°ããèªåçã«æå¹ã«ãªããã¨ã«ãªãã¾ãã
# èªåçã«æå¹ã«ãªã use utf8;
ãã§ããããã½ã¼ã¹ã³ã¼ãã¨ãã³ãã¬ã¼ãã§è¨è¿°ããæååã¯ããã¹ã¦å é¨æååã«ãªãã¾ãã
ãã³ãã¬ã¼ãã«æç»ããã¨ãã¯å é¨æååãUTF-8ãã¤ãæååã«èªåçã«å¤æ
ããã³ãã¬ã¼ãã«æç»ããã¨ãã¯ãå é¨æååãUTF-8ãã¤ãæååã«èªåçã«å¤æããã¾ãã
get '/' => sub { my $self = shift; $c->render('index', message => 'ããããã'); }; @@ index.html <% my $message = stash('message'); %> æ¥æ¬èªãæ¸ã <%= $message %>
ãæ®éã«è¨è¿°ããã°ãæ®éã«èªåå¤æãããã®ã§ãæ®æ®µã¯ç¹å¥ã«æèããå¿ è¦ã¯ãªãã§ãã
ãã©ã¼ã ããåãåãã¨ãã¯UTF-8ãã¤ãæååãå é¨æååã«èªåçã«å¤æ
ããã©ã¼ã ããæååãåãåãã¨ãã¯ãèªåçã«å é¨æååã«å¤æããã¾ãã
post '/' => sub { my $self = shift; my $message = $self->param('message'); ... }
ãparamã¡ã½ããã§åãåã£ãæååã¯å é¨æååã¸ã¨èªåçã«å¤æããã¦ãã¾ãã
ããã®ããã«Mojoliciousã§ã¯ãã¤ãæååã¨å é¨æååã®å¤æãèªåçã«è¡ã£ã¦ãããã®ã§ãæ®æ®µã¯ãã¾ãæèããå¿ è¦ãããã¾ããããä»çµã¿èªä½ã¯è¦ãã¦ããã¦ã»ããã¨æãã¾ãã