Encode::Guess:guess_encoding gives different results in different contexts The Next CEO of Stack OverflowFixing a file consisting of both UTF-8 and Windows-1252How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How can I convert an input file to UTF-8 encoding in Perl?Writing Unicode text to a text file?Reading lines of text in unknown encodingHow can I be sure of the file encoding?Force encode from US-ASCII to UTF-8 (iconv)Python: Encoding Error - content of web pageChange file encoding for PostgreSQL w/PerlCan Encode::Guess tell utf-8 from iso-8859-1?Character Encodings compability with ASCII

If/When UK leaves the EU, can a future goverment conduct a referendum to join the EU?

How to Reset Passwords on Multiple Websites Easily?

Multiple labels for a single equation

Novel about a guy who is possessed by the divine essence and the world ends?

What was the first Unix version to run on a microcomputer?

sp_blitzCache results Memory grants

Do I need to enable Dev Hub in my PROD Org?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Indicator light circuit

How did people program for Consoles with multiple CPUs?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

How do I avoid eval and parse?

How powerful is the invisibility granted by the Gloom Stalker ranger's Umbral Sight feature?

What can we do to stop prior company from asking us questions?

Sending manuscript to multiple publishers

Won the lottery - how do I keep the money?

How does the mv command work with external drives?

Should I tutor a student who I know has cheated on their homework?

Complex fractions

Can you replace a racial trait cantrip when leveling up?

Has this building technique been used in an official set?

How to solve a differential equation with a term to a power?

Why does standard notation not preserve intervals (visually)

Can I run my washing machine drain line into a condensate pump so it drains better?



Encode::Guess:guess_encoding gives different results in different contexts



The Next CEO of Stack OverflowFixing a file consisting of both UTF-8 and Windows-1252How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How can I convert an input file to UTF-8 encoding in Perl?Writing Unicode text to a text file?Reading lines of text in unknown encodingHow can I be sure of the file encoding?Force encode from US-ASCII to UTF-8 (iconv)Python: Encoding Error - content of web pageChange file encoding for PostgreSQL w/PerlCan Encode::Guess tell utf-8 from iso-8859-1?Character Encodings compability with ASCII










1















I have the following sub that opens a text file and attempts to ensure its encoding is one of either UTF-8, ISO-8859-15 or ASCII.



The problem I have with it is different behaviours in interactive vs. non-interactive use.



  • when I run interactively with a file that contains a UTF-8 line, $decoder is, as expected, a reference object whose name returns utf8 for that line.


  • non-interactively (as it runs as part of a subversion commit hook) guess_encoding returns a scalar string of value utf8 or iso-8859-15 for the utf8 check line, and iso-8859-15 or utf8 for the other two lines.


I can't for the life of me, work out where the difference in behaviour is coming from. If I force the encoding of the open to say <:encoding(utf8), it accepts every line as UTF-8 without question.



The problem is I can't assume that every file it receives will be UTF-8, so I don't want to force the encoding as a work-around. Another potential workaround is to parse the scalar text, but that just seems messy, especially when it seems to work correctly in an interactive context.



From the shell, I've tried overriding $LANG (as non-interactively that isn't set, nor are any of the LC_ variables), however the interactive version still runs correctly.



The commented out line that reports $Encode::Guess::NoUTFAutoGuess returns 0 in both interactive and non-interactive use when commented in.



Ultimately, the one thing we're trying to prevent is having UTF-16 or other wide-char encodings in our repository (as some of our tooling doesn't play well with it): I thought that looking for a white-list of encodings is an easier job than looking for a black-list of encodings.



sub checkEncoding

my ($file) = @_;

my ($b1, $b2, $b3);
my $encoding = "";
my $retval = 1;
my $line = 0;

say("Checking encoding of $file");
#say($Encode::Guess::NoUTFAutoGuess);
open (GREPFILE, "<", $file);
while (<GREPFILE>)
chomp($_);
$line++;

my $decoder = Encode::Guess::guess_encoding($_, 'utf8');
say("A: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'iso-8859-15') unless ref $decoder;
say("B: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'ascii') unless ref $decoder;
say("C: $decoder");

if (ref $decoder)
$encoding = $decoder->name;
else
say "Mis-identified encoding '$decoder' on line $line: [$_]";
my $z = unpack('H*', $_);
say $z;
$encoding = $decoder;
$retval = 0;


last if ($retval == 0);

close GREPFILE;

return $retval;










share|improve this question



















  • 1





    I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

    – Silvar
    Mar 8 at 15:45







  • 1





    I also think you're supposed to use <:raw in the open().

    – Silvar
    Mar 8 at 15:51











  • From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

    – Tom Blodget
    Mar 8 at 16:21











  • Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

    – ikegami
    Mar 8 at 21:05











  • Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

    – Chris J
    Mar 11 at 12:14
















1















I have the following sub that opens a text file and attempts to ensure its encoding is one of either UTF-8, ISO-8859-15 or ASCII.



The problem I have with it is different behaviours in interactive vs. non-interactive use.



  • when I run interactively with a file that contains a UTF-8 line, $decoder is, as expected, a reference object whose name returns utf8 for that line.


  • non-interactively (as it runs as part of a subversion commit hook) guess_encoding returns a scalar string of value utf8 or iso-8859-15 for the utf8 check line, and iso-8859-15 or utf8 for the other two lines.


I can't for the life of me, work out where the difference in behaviour is coming from. If I force the encoding of the open to say <:encoding(utf8), it accepts every line as UTF-8 without question.



The problem is I can't assume that every file it receives will be UTF-8, so I don't want to force the encoding as a work-around. Another potential workaround is to parse the scalar text, but that just seems messy, especially when it seems to work correctly in an interactive context.



From the shell, I've tried overriding $LANG (as non-interactively that isn't set, nor are any of the LC_ variables), however the interactive version still runs correctly.



The commented out line that reports $Encode::Guess::NoUTFAutoGuess returns 0 in both interactive and non-interactive use when commented in.



Ultimately, the one thing we're trying to prevent is having UTF-16 or other wide-char encodings in our repository (as some of our tooling doesn't play well with it): I thought that looking for a white-list of encodings is an easier job than looking for a black-list of encodings.



sub checkEncoding

my ($file) = @_;

my ($b1, $b2, $b3);
my $encoding = "";
my $retval = 1;
my $line = 0;

say("Checking encoding of $file");
#say($Encode::Guess::NoUTFAutoGuess);
open (GREPFILE, "<", $file);
while (<GREPFILE>)
chomp($_);
$line++;

my $decoder = Encode::Guess::guess_encoding($_, 'utf8');
say("A: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'iso-8859-15') unless ref $decoder;
say("B: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'ascii') unless ref $decoder;
say("C: $decoder");

if (ref $decoder)
$encoding = $decoder->name;
else
say "Mis-identified encoding '$decoder' on line $line: [$_]";
my $z = unpack('H*', $_);
say $z;
$encoding = $decoder;
$retval = 0;


last if ($retval == 0);

close GREPFILE;

return $retval;










share|improve this question



















  • 1





    I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

    – Silvar
    Mar 8 at 15:45







  • 1





    I also think you're supposed to use <:raw in the open().

    – Silvar
    Mar 8 at 15:51











  • From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

    – Tom Blodget
    Mar 8 at 16:21











  • Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

    – ikegami
    Mar 8 at 21:05











  • Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

    – Chris J
    Mar 11 at 12:14














1












1








1








I have the following sub that opens a text file and attempts to ensure its encoding is one of either UTF-8, ISO-8859-15 or ASCII.



The problem I have with it is different behaviours in interactive vs. non-interactive use.



  • when I run interactively with a file that contains a UTF-8 line, $decoder is, as expected, a reference object whose name returns utf8 for that line.


  • non-interactively (as it runs as part of a subversion commit hook) guess_encoding returns a scalar string of value utf8 or iso-8859-15 for the utf8 check line, and iso-8859-15 or utf8 for the other two lines.


I can't for the life of me, work out where the difference in behaviour is coming from. If I force the encoding of the open to say <:encoding(utf8), it accepts every line as UTF-8 without question.



The problem is I can't assume that every file it receives will be UTF-8, so I don't want to force the encoding as a work-around. Another potential workaround is to parse the scalar text, but that just seems messy, especially when it seems to work correctly in an interactive context.



From the shell, I've tried overriding $LANG (as non-interactively that isn't set, nor are any of the LC_ variables), however the interactive version still runs correctly.



The commented out line that reports $Encode::Guess::NoUTFAutoGuess returns 0 in both interactive and non-interactive use when commented in.



Ultimately, the one thing we're trying to prevent is having UTF-16 or other wide-char encodings in our repository (as some of our tooling doesn't play well with it): I thought that looking for a white-list of encodings is an easier job than looking for a black-list of encodings.



sub checkEncoding

my ($file) = @_;

my ($b1, $b2, $b3);
my $encoding = "";
my $retval = 1;
my $line = 0;

say("Checking encoding of $file");
#say($Encode::Guess::NoUTFAutoGuess);
open (GREPFILE, "<", $file);
while (<GREPFILE>)
chomp($_);
$line++;

my $decoder = Encode::Guess::guess_encoding($_, 'utf8');
say("A: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'iso-8859-15') unless ref $decoder;
say("B: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'ascii') unless ref $decoder;
say("C: $decoder");

if (ref $decoder)
$encoding = $decoder->name;
else
say "Mis-identified encoding '$decoder' on line $line: [$_]";
my $z = unpack('H*', $_);
say $z;
$encoding = $decoder;
$retval = 0;


last if ($retval == 0);

close GREPFILE;

return $retval;










share|improve this question
















I have the following sub that opens a text file and attempts to ensure its encoding is one of either UTF-8, ISO-8859-15 or ASCII.



The problem I have with it is different behaviours in interactive vs. non-interactive use.



  • when I run interactively with a file that contains a UTF-8 line, $decoder is, as expected, a reference object whose name returns utf8 for that line.


  • non-interactively (as it runs as part of a subversion commit hook) guess_encoding returns a scalar string of value utf8 or iso-8859-15 for the utf8 check line, and iso-8859-15 or utf8 for the other two lines.


I can't for the life of me, work out where the difference in behaviour is coming from. If I force the encoding of the open to say <:encoding(utf8), it accepts every line as UTF-8 without question.



The problem is I can't assume that every file it receives will be UTF-8, so I don't want to force the encoding as a work-around. Another potential workaround is to parse the scalar text, but that just seems messy, especially when it seems to work correctly in an interactive context.



From the shell, I've tried overriding $LANG (as non-interactively that isn't set, nor are any of the LC_ variables), however the interactive version still runs correctly.



The commented out line that reports $Encode::Guess::NoUTFAutoGuess returns 0 in both interactive and non-interactive use when commented in.



Ultimately, the one thing we're trying to prevent is having UTF-16 or other wide-char encodings in our repository (as some of our tooling doesn't play well with it): I thought that looking for a white-list of encodings is an easier job than looking for a black-list of encodings.



sub checkEncoding

my ($file) = @_;

my ($b1, $b2, $b3);
my $encoding = "";
my $retval = 1;
my $line = 0;

say("Checking encoding of $file");
#say($Encode::Guess::NoUTFAutoGuess);
open (GREPFILE, "<", $file);
while (<GREPFILE>)
chomp($_);
$line++;

my $decoder = Encode::Guess::guess_encoding($_, 'utf8');
say("A: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'iso-8859-15') unless ref $decoder;
say("B: $decoder");
$decoder = Encode::Guess::guess_encoding($_, 'ascii') unless ref $decoder;
say("C: $decoder");

if (ref $decoder)
$encoding = $decoder->name;
else
say "Mis-identified encoding '$decoder' on line $line: [$_]";
my $z = unpack('H*', $_);
say $z;
$encoding = $decoder;
$retval = 0;


last if ($retval == 0);

close GREPFILE;

return $retval;







perl character-encoding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 12:20







Chris J

















asked Mar 8 at 14:32









Chris JChris J

24.3k45294




24.3k45294







  • 1





    I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

    – Silvar
    Mar 8 at 15:45







  • 1





    I also think you're supposed to use <:raw in the open().

    – Silvar
    Mar 8 at 15:51











  • From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

    – Tom Blodget
    Mar 8 at 16:21











  • Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

    – ikegami
    Mar 8 at 21:05











  • Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

    – Chris J
    Mar 11 at 12:14













  • 1





    I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

    – Silvar
    Mar 8 at 15:45







  • 1





    I also think you're supposed to use <:raw in the open().

    – Silvar
    Mar 8 at 15:51











  • From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

    – Tom Blodget
    Mar 8 at 16:21











  • Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

    – ikegami
    Mar 8 at 21:05











  • Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

    – Chris J
    Mar 11 at 12:14








1




1





I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

– Silvar
Mar 8 at 15:45






I thought you were supposed to feed Encode::Guess the entire data set (file) to get the most accurate results? To me it seems you're trying to guess the encoding for each line separately. Even for a UTF-8 file, some lines may not have byte combinations that make it look like UTF-8, so for those lines, the guessing will also consider ASCII or ISO-8859-15.

– Silvar
Mar 8 at 15:45





1




1





I also think you're supposed to use <:raw in the open().

– Silvar
Mar 8 at 15:51





I also think you're supposed to use <:raw in the open().

– Silvar
Mar 8 at 15:51













From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

– Tom Blodget
Mar 8 at 16:21





From the known knowns perspective, ISO-8859-1=Yes. No byte value or sequence of values is incompatible with ISO-8859-1.

– Tom Blodget
Mar 8 at 16:21













Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

– ikegami
Mar 8 at 21:05





Wait, in one place you says ISO-8859-1, but the rest you say -15. Is -1 a typo?

– ikegami
Mar 8 at 21:05













Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

– Chris J
Mar 11 at 12:14






Hi all, thanks for comments - changes made to slurp the whole file and give guess_encoding() that. However the central problem remains: when ran interactively, $decoder ends up being a reference type, when ran via the SVN hooks non-interatively, $decoder ends up being a scalar. I want to understand why that should be different?

– Chris J
Mar 11 at 12:14













1 Answer
1






active

oldest

votes


















1














No need to guess. For the specific options of UTF-8, ISO-8859-1 and US-ASCII, you can use Encoding::FixLatin's fix_latin. It's virtually guaranteed to succeed.



That said, I think the use of ISO-8859-1 in the OP is a typo for ISO-8859-15.



The method used by fix_latin would work just as well for ISO-8859-15 as it does for ISO-8859-1. It's simply a question of replacing _init_byte_map with the following:



sub _init_byte_map 
foreach my $i (0x80..0xFF)
my $byte = chr($i);
my $utf8 = Encode::from_to($byte, 'iso-8859-15', 'UTF-8');
$byte_map->$byte = $utf8;




Alternatively, if you're willing to assume the data is all of one encoding or another (rather than a mix), you could also use the following approach:



my $text;
if (!eval Encode::LEAVE_SRC);
1 # No exception
)
$text = decode("ISO-8859-15", $bytes);



Keep in mind that US-ASCII is a proper subset of both UTF-8 and ISO-8859-15, so it doesn't need to be handled specially.






share|improve this answer

























  • Added to answer.

    – ikegami
    Mar 8 at 21:20











  • Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

    – Chris J
    Mar 11 at 12:17












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065319%2fencodeguessguess-encoding-gives-different-results-in-different-contexts%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














No need to guess. For the specific options of UTF-8, ISO-8859-1 and US-ASCII, you can use Encoding::FixLatin's fix_latin. It's virtually guaranteed to succeed.



That said, I think the use of ISO-8859-1 in the OP is a typo for ISO-8859-15.



The method used by fix_latin would work just as well for ISO-8859-15 as it does for ISO-8859-1. It's simply a question of replacing _init_byte_map with the following:



sub _init_byte_map 
foreach my $i (0x80..0xFF)
my $byte = chr($i);
my $utf8 = Encode::from_to($byte, 'iso-8859-15', 'UTF-8');
$byte_map->$byte = $utf8;




Alternatively, if you're willing to assume the data is all of one encoding or another (rather than a mix), you could also use the following approach:



my $text;
if (!eval Encode::LEAVE_SRC);
1 # No exception
)
$text = decode("ISO-8859-15", $bytes);



Keep in mind that US-ASCII is a proper subset of both UTF-8 and ISO-8859-15, so it doesn't need to be handled specially.






share|improve this answer

























  • Added to answer.

    – ikegami
    Mar 8 at 21:20











  • Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

    – Chris J
    Mar 11 at 12:17
















1














No need to guess. For the specific options of UTF-8, ISO-8859-1 and US-ASCII, you can use Encoding::FixLatin's fix_latin. It's virtually guaranteed to succeed.



That said, I think the use of ISO-8859-1 in the OP is a typo for ISO-8859-15.



The method used by fix_latin would work just as well for ISO-8859-15 as it does for ISO-8859-1. It's simply a question of replacing _init_byte_map with the following:



sub _init_byte_map 
foreach my $i (0x80..0xFF)
my $byte = chr($i);
my $utf8 = Encode::from_to($byte, 'iso-8859-15', 'UTF-8');
$byte_map->$byte = $utf8;




Alternatively, if you're willing to assume the data is all of one encoding or another (rather than a mix), you could also use the following approach:



my $text;
if (!eval Encode::LEAVE_SRC);
1 # No exception
)
$text = decode("ISO-8859-15", $bytes);



Keep in mind that US-ASCII is a proper subset of both UTF-8 and ISO-8859-15, so it doesn't need to be handled specially.






share|improve this answer

























  • Added to answer.

    – ikegami
    Mar 8 at 21:20











  • Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

    – Chris J
    Mar 11 at 12:17














1












1








1







No need to guess. For the specific options of UTF-8, ISO-8859-1 and US-ASCII, you can use Encoding::FixLatin's fix_latin. It's virtually guaranteed to succeed.



That said, I think the use of ISO-8859-1 in the OP is a typo for ISO-8859-15.



The method used by fix_latin would work just as well for ISO-8859-15 as it does for ISO-8859-1. It's simply a question of replacing _init_byte_map with the following:



sub _init_byte_map 
foreach my $i (0x80..0xFF)
my $byte = chr($i);
my $utf8 = Encode::from_to($byte, 'iso-8859-15', 'UTF-8');
$byte_map->$byte = $utf8;




Alternatively, if you're willing to assume the data is all of one encoding or another (rather than a mix), you could also use the following approach:



my $text;
if (!eval Encode::LEAVE_SRC);
1 # No exception
)
$text = decode("ISO-8859-15", $bytes);



Keep in mind that US-ASCII is a proper subset of both UTF-8 and ISO-8859-15, so it doesn't need to be handled specially.






share|improve this answer















No need to guess. For the specific options of UTF-8, ISO-8859-1 and US-ASCII, you can use Encoding::FixLatin's fix_latin. It's virtually guaranteed to succeed.



That said, I think the use of ISO-8859-1 in the OP is a typo for ISO-8859-15.



The method used by fix_latin would work just as well for ISO-8859-15 as it does for ISO-8859-1. It's simply a question of replacing _init_byte_map with the following:



sub _init_byte_map 
foreach my $i (0x80..0xFF)
my $byte = chr($i);
my $utf8 = Encode::from_to($byte, 'iso-8859-15', 'UTF-8');
$byte_map->$byte = $utf8;




Alternatively, if you're willing to assume the data is all of one encoding or another (rather than a mix), you could also use the following approach:



my $text;
if (!eval Encode::LEAVE_SRC);
1 # No exception
)
$text = decode("ISO-8859-15", $bytes);



Keep in mind that US-ASCII is a proper subset of both UTF-8 and ISO-8859-15, so it doesn't need to be handled specially.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 21:18

























answered Mar 8 at 20:59









ikegamiikegami

267k11178403




267k11178403












  • Added to answer.

    – ikegami
    Mar 8 at 21:20











  • Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

    – Chris J
    Mar 11 at 12:17


















  • Added to answer.

    – ikegami
    Mar 8 at 21:20











  • Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

    – Chris J
    Mar 11 at 12:17

















Added to answer.

– ikegami
Mar 8 at 21:20





Added to answer.

– ikegami
Mar 8 at 21:20













Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

– Chris J
Mar 11 at 12:17






Hiya, ultimately I'm not looking to do a decode, but if that's going to be the most reliable way to detect encoding I'll run with it (the intended behaviour is to throw an error on an encoding that's not acceptable, not convert between encodings). My primary concern is the different behaviour in guess_encoding in different contexts (i.e., interactive vs. non-interactive).

– Chris J
Mar 11 at 12:17




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065319%2fencodeguessguess-encoding-gives-different-results-in-different-contexts%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page