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öäüÖÄÜß