use strict; use warnings; use Win32::Console::Ansi; # converts output for code page 850 to OEM code page my $isRedirected = ! -t STDOUT; my $Str = 'äöüÄÖÜß' . "\n"; # this string has default encoding iso-8859-1 # if STDOUT is redirected to a file, use unicode encoding, otherwise use default if ($isRedirected) { if (!defined binmode STDOUT, ':encoding(UTF-8)') { warn "binmode failed: $!\n"; } utf8::encode($Str); } # output string with a hexdump if (!print 'string: ', hd($Str), $Str){ warn "print failed\n"; } # With a redirected file I end up with a UTF-16 LE BOM encoded file with wrong content :-( # for comparison, this works as expected (produces utf8 content) open(my $fh, '>:encoding(UTF-8)', 'utf8_2') or die "can't open file for writing:$!\n"; print $fh $Str or warn "print to file failed\n"; close $fh or warn "close file failed\n"; # hexdump sub hd { my $input = shift; return join(' ', unpack('(H2)*', $input)), "\n"; }