Changing character sets for ALL files in a directory to UTF-8


I have over 300 script files in a directory that were created using a mixture of the following character sets:

ISO 8859-1

This causes a number of problems.

For example, when displayed as a webpage, the header could be created with one charset, the body with another and the footer with another.

So I need to convert the contents of ALL files with the extension .pl or .cgi or .php or .txt or .tpl to UTF-8.

How can this be done with PERL?

LVL 16
Who is Participating?
Are these CGI files?  Do you mean to say that the Perl scripts create web pages that use XML document type declarations (DTD) and that these declarations specify different character types?

So, some web pages created by these scripts have something like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

while others might have:

<?xml version="1.0" encoding="ISO 8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

and you need them all to be consistant?

I guess I might be confused about what you mean by the "script files...were created using a mixture of...character sets".  Do you mean the files *themselves* were created (written) with mixed character sets, or the files that the scripts create as *output* contain mixed character sets?
If it's what I think, it'd be a simple regular expression problem.  For example:

#!/usr/bin/perl -w
use strict;

while (<DATA>) {

<?xml version="1.0" encoding="Windows-1251"?>
<?xml version="1.0" encoding="Windows-1252"?>
<?xml version="1.0" encoding="ISO 8859-1"?>

Couple this with File::Find to find all your .pl , .cgi, .php, .txt or .tpl files, open each matching file, replace the encoding line with the one you want, and print the file to a new file.
# I guess you need something like following code snippet:

use Encode;
# ... some code to read the file content here
from_to($content, "cp1250", "utf8");
# .. some other file
from_to($content, "iso-8859-1", "utf8");

# please read  man Encode carefully first
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.