Skip to content

Instantly share code, notes, and snippets.

@suzusime
Last active December 24, 2020 16:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suzusime/c5b7f5f08bfc9b0c8a85d286bd094da1 to your computer and use it in GitHub Desktop.
Save suzusime/c5b7f5f08bfc9b0c8a85d286bd094da1 to your computer and use it in GitHub Desktop.
perlでスクリプトを書くときのテンプレ
#!/usr/bin/env perl
use strict;
use warnings;
use 5.014;
use utf8;
use open ':encoding(UTF-8)';
use Encode::Locale;
binmode(STDIN, ":encoding(console_in)");
binmode(STDOUT, ":encoding(console_out)");
binmode(STDERR, ":encoding(console_out)");
Encode::Locale::decode_argv;
say "日本語表現";
use strict;
use warnings;
use 5.014;

定型文。5.014はUnicodeがそれなりに使えそうな最低限のバージョンということで。

use utf8;

ソースファイル中の文字列リテラルが内部表現に変換されるようにする。スクリプトをUTF-8で保存せよ。

use open ':encoding(UTF-8)';

open でのファイルのIO (PerlIO)での文字コードをUTF-8にする。もちろん入出力したいファイルがUTF-8ではない場合は変える必要がある。

:encoding(utf8):encoding(UTF-8) は違うらしい(参照)。読み込みの安全性を考えるとUTF-8のほうが良いらしいのでそちらにした。

use Encode::Locale;
binmode(STDIN, ":encoding(console_in)");
binmode(STDOUT, ":encoding(console_out)");
binmode(STDERR, ":encoding(console_out)");
Encode::Locale::decode_argv;

標準入出力の文字コードを端末のものに合わせる。これで何も考えなくても普通に say とかできる。 use Encode::Localeconsole_in などを使うのに必要。 Encode::Locale::decode_argv;はコマンドライン引数もデコードするようにする。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment