my $test = 0; use warnings; use bytes; use Benchmark; use Encode qw(encode_utf8 decode_utf8); my $xml; { my $isUTF = 1; my $sub = sub {$isUTF = 0}; sub byPack { $SIG{__WARN__} = $sub; no warnings 'void'; my @a=unpack( 'U0U*', $xml); delete $SIG{__WARN__}; return $isUTF; } } sub byRegExp { my $bad_utf8 = 0; while($xml =~ /(?=[\x80-\xFF])(?:[\xC0-\xFF][\x80-\xBF]+|(.))/g and !$bad_utf8) { $bad_utf8++ if defined $1; } return !$bad_utf8; } sub byDecode { if (decode_utf8($xml)) { return 1 } else { return 0 } } print "OK\n"; open XML, '}; close XML; if ($test) { print "byPack=".byPack()."\n"; print "byRegExp=".byRegExp()."\n"; print "byDecode=".byDecode()."\n"; } else { timethese (10000, { byPack => \&byPack, byRegExp => \&byRegExp, byDecode => \&byDecode, }); } print "BAD\n"; open XML, '}; close XML; if ($test) { print "byPack=".byPack()."\n"; print "byRegExp=".byRegExp()."\n"; print "byDecode=".byDecode()."\n"; } else { timethese (10000, { byPack => \&byPack, byRegExp => \&byRegExp, byDecode => \&byDecode, }); } __END__ OK Benchmark: timing 10000 iterations of byDecode, byPack, byRegExp... byDecode: 0 wallclock secs ( 0.22 usr + 0.00 sys = 0.22 CPU) @ 45662.10/s (n=10000) (warning: too few iterations for a reliable count) byPack: 15 wallclock secs (15.17 usr + 0.00 sys = 15.17 CPU) @ 659.11/s (n=10000) byRegExp: 5 wallclock secs ( 4.22 usr + 0.00 sys = 4.22 CPU) @ 2370.79/s (n=10000) BAD Benchmark: timing 10000 iterations of byDecode, byPack, byRegExp... byDecode: 0 wallclock secs ( 0.08 usr + 0.00 sys = 0.08 CPU) @ 128205.13/s (n=10000) (warning: too few iterations for a reliable count) byPack: 15 wallclock secs (15.42 usr + 0.00 sys = 15.42 CPU) @ 648.42/s (n=10000) byRegExp: 5 wallclock secs ( 4.25 usr + 0.00 sys = 4.25 CPU) @ 2352.94/s (n=10000)