use encoding 'utf8'実例

ソース:utf8で記述

#!/usr/bin/perl -w
use strict;
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

not UTF-8 Flag

ソース:utf8

#!/usr/bin/perl -w
use strict;
use utf8;
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

UTF-8 Flag

ソース:utf8

#!/usr/bin/perl -w
use strict;
use utf8;
print utf8::is_utf8("hoge") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

not UTF-8 Flag

utf8プラグマは宣言すると、マルチバイトの文字列にutf8フラグがつくらすぃ。

ソース:euc-jp

#!/usr/bin/perl -w
use strict;
use utf8;
use encoding 'utf8';
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

Malformed UTF-8 character (unexpected continuation byte 0xa4, with no preceding
start byte) at ./utf8_test.pl line 8.
Malformed UTF-8 character (unexpected continuation byte 0xb2, with no preceding
start byte) at ./utf8_test.pl line 8.
UTF-8 Flag

ソース:euc-jp

#!/usr/bin/perl -w
use strict;
#use utf8;
use encoding 'utf8';
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

Malformed UTF-8 character (unexpected continuation byte 0xa4, with no preceding
start byte) at ./utf8_test.pl line 8.
Malformed UTF-8 character (unexpected continuation byte 0xb2, with no preceding
start byte) at ./utf8_test.pl line 8.
UTF-8 Flag

どちらもUTF-8フラグついてます。

ソース:euc-jp

#!/usr/bin/perl -w
use strict;
#use utf8;
#use encoding 'utf8';
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';

結果

not UTF-8 Flag

当然ですね。。

ソース:euc-jp

#!/usr/bin/perl -w
use strict;
use utf8;
use encoding 'utf8';
{
no utf8;
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';
}

結果

Malformed UTF-8 character (unexpected continuation byte 0xa4, with no preceding
start byte) at ./utf8_test.pl line 8.
Malformed UTF-8 character (unexpected continuation byte 0xb2, with no preceding
start byte) at ./utf8_test.pl line 8.
UTF-8 Flag

ソース:euc-jp

#!/usr/bin/perl -w
use strict;
use utf8;
#use encoding 'utf8';
{
no utf8;
print utf8::is_utf8("ほげ") ? 'UTF-8 Flag' : 'not UTF-8 Flag';
}

結果

not UTF-8 Flag

use encodingしていれば、例えレキシカルスコープでno utf8としても、
utf8フラグがついてしまう。