I need to convert all kinds of files to ANSI (8859-1) except ANSI (8859-1) files, skip those.
When I change my code and try to convert files into utf8 it doesn't work anymore. Seems like the
decode line only works like this using decode on utf8. It doesn't distinguish ANSI on ISO.
Or am I doing something wrong?
utf8 to ansi
#!/usr/bin/perl -w
use strict;
use warnings;
use Encode qw(encode decode);
my $sFile = "";
my $sLine = "";
my $sCodepoints = "";
if ( $#ARGV == 0 )
{
$sFile = $ARGV[0] ;
if ( ! -e $sFile )
{
die "File '$sFile' doesn't exist!";
}
}
open( FILE, "<", "$sFile") or die "Couldn't open file '$sFile'!";
{ # slurp file into string
local $/;
$sLine = <FILE>;
close( FILE );
}
eval { $sCodepoints = decode( "utf8", $sLine, Encode::FB_CROAK ) };
if ( $@ )
{ # input was not utf8
print "> No UTF-8, maybe ISO-8859-1 ?\n";
$sCodepoints = $sLine;
}
open( FILENEW, ">:encoding(iso-8859-1)", "$sFile.new" ) or die "Couldn
+'t open file '$sFile.new'!";
print FILENEW $sCodepoints;
close( FILENEW );
ansi to utf8
#!/usr/bin/perl -w
use strict;
use warnings;
use Encode qw(encode decode);
my $sFile = "";
my $sLine = "";
my $sCodepoints = "";
if ( $#ARGV == 0 )
{
$sFile = $ARGV[0] ;
if ( ! -e $sFile )
{
die "File '$sFile' doesn't exist!";
}
}
open( FILE, "<", "$sFile") or die "Couldn't open file '$sFile'!";
{ # slurp file into string
local $/;
$sLine = <FILE>;
close( FILE );
}
eval { $sCodepoints = decode( "iso-8859-1", $sLine, Encode::FB_CROAK )
+ };
if ( $@ )
{ # input was not iso-8859-1
print "> No ISO-8859-1, maybe UTF8 ?\n";
$sCodepoints = $sLine;
}
open( FILENEW, ">:encoding(utf8)", "$sFile.new" ) or die "Couldn't ope
+n file '$sFile.new'!";
print FILENEW $sCodepoints;
close( FILENEW );
I created two test-files
ansi.txt and
utf8.txt for testing. Content of the files:
1TestöäüÖÄÜß
2TestöäüÖÄÜß
3TestöäüÖÄÜß
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.