use DecodedMsg; tie $! , "DecodedMsg"; #### use strict; use warnings; use Encode qw(decode encode); sub show{ printf "is_utf8=%d, len=%d, msg=%s\n", utf8::is_utf8($_), length($_), $_; } #byte string utf8 hiragana my $byte_error_msg=encode('UTF-8', join('', map{pack('U',$_)} 0x3042 .. 0x3052)); print "#test1: with byets\n"; $_ = $byte_error_msg ; show; print "#test2: with decoded char\n"; $_ = decode("UTF-8", $byte_error_msg); show; print "#test3 with tied variable ... seems working\n"; {package DecodedMsg; use Encode qw(decode); sub TIESCALAR { my $class=shift; print "class=$class\n"; return bless( {} , $class ); } sub STORE{ my $self=shift; print "###in store arg=$_[0]\n"; $self->{val}= $_[0]; } sub FETCH { my $self=shift; if( utf8::is_utf8( $self->{val} ) ){ return $self->{val}; } else { print "#in fetch ... return decoded\n"; return decode('UTF-8', $self->{val}) } } 1; } tie $_, "DecodedMsg"; #tie $_ to DecodedMsg $_ = $byte_error_msg; show; print "#test4 with tied variable ... with system error\n"; tie $!, "DecodedMsg"; open(my $fh, "<", " /the/path/to/nowhere"); $_ =$!; show;