Search code examples
perlfileencode

convert encoding format


After super-searching a method to convert the encoding file in perl, I'm always asking myself what is the best way to do this.

My problem is very simple : I have many files in differents encoding (UTF-8, ISO-8859-1, windows-1252 ... ) and , I want to convert all this files in ISO-8859-1.


Solution

  • Text::Iconv is very effective and very fast in converting from and to most encodings. It's also very simple to use

    use Text::Iconv;
    $converter = Text::Iconv->new("fromcode", "tocode");
    $converted = $converter->convert("Text to convert");
    

    A simple example

    use Text::Iconv;
    my $converter = Text::Iconv->new("utf8", "iso-8859-1");
    my $iso_8859_1_string = $converter->convert($some_utf8_string);
    

    If you dont know the encoding of the file you are trying to convert, you can use Encode::Detect::Detector to find the encoding automatically.

    use Encode::Detect::Detector;
    my $charset = detect($string);