MIME変換 (module)MIME-Base64

back
オプションモジュール
http://search.cpan.org/~gaas/MIME-Base64-3.01/Base64.pm

MIME デコード / MIME エンコードする。

----
use MIME::Base64;

$string = "sample string";
print $string, "\n";
$encoded = encode_base64($string);
print $encoded;
$decoded = decode_base64($encoded);
print $decoded, "\n";
----

hmiyazaki@mozzarella:~/work/prog/perl$ ./test.pl 
sample string
c2FtcGxlIHN0cmluZw==
sample string


エンコードする際は、自動で 76 文字で改行が入り折り返す。
また、デコードの際は、76 文字の折り返しが合ってもかまわない。

----
$string = "sample string. Programming Tools Perl5 desktop reference #3  by O'REILLY";
print $string, "\n";
$encoded = encode_base64($string);
print $encoded;
$decoded = decode_base64($encoded);
print $decoded, "\n";
----

hmiyazaki@mozzarella:~/work/prog/perl$ ./test.pl 
sample string. Programming Tools Perl5 desktop reference #3  by O'REILLY
c2FtcGxlIHN0cmluZy4gUHJvZ3JhbW1pbmcgVG9vbHMgUGVybDUgZGVza3RvcCByZWZlcmVuY2Ug
IzMgIGJ5IE8nUkVJTExZ
sample string. Programming Tools Perl5 desktop reference #3  by O'REILLY


※ メールの件名などを B エンコードする際は、
(1) 日本語部分を iso-2022-jp へ変換する
(2) =?ISO-2022-JP?B?= (だっけか?)を付加する
を忘れないこと

----
対象ファイルを全部 Base64 エンコードする場合は

open(F, "file");
while (<F>) {
  print encode_base64($_);
}
close(F);

だと file の改行ごとのエンコードになるので NG

$/ = "";
で、ファイルを一気によみこむか、

while (read(STDIN, $buf, xx*57)) {
  print encode_base64($buf);
}

と、57 バイト毎(57 = 76 * 6/8)にエンコードすること。
xx は、何回かまとめて処理できるように適当な数字をいれておけ

back