http://qs321.pair.com?node_id=620803

An example round trip

The steps below demonstrate how to accept UTF-8 strings from outside, store them in MySQL, retrieve them from the database, and re-output them

Manual, or with Automatic with PerlIO layers MySQL::dbd > v 4 --------------- ---------------- --------- --------- ----- +----- ¦ UTF-8 ¦ ---decode_utf8()->> ¦ Perl ¦ ---encode_utf8()->> ¦ UTF +-8 ¦ ¦ Console ¦ <<-encode_utf8()--- ¦ strings ¦ <<-decode_utf8()--- ¦ MySQ +L DB ¦ --------- --------- ----- +-----
  1. Create a table in MySQL which uses the UTF-8 character set:

    This step ensures that all UTF-8 aware programs that interact with this database know to treat the stored data as UTF-8

    CREATE TABLE test_db.test ( string VARCHAR(50) ) CHARACTER SET utf +8;
  2. Get a UTF-8 string:

    This step accepts a string of bytes representing a UTF-8 string, and converts them into Perl's internal string format.

    • From a UTF-8 console:
      use Encode qw( decode_utf8 ); my $string = <>; my $utf8_string = decode_utf8($string);
    • or, from an ISO-8859-1 console:
      use Encode qw( decode ); my $iso_8859_string = <>; my $utf8_string = decode('ISO-8859-1',$iso_8859_string);
    • or from within a Perl script:
      use utf8; # Tells Perl that the script itself is written i +n UTF-8 my $utf8_string = "UTF-8 string with special chars: ñ æ ô";
  3. Open a UTF-8 enabled database connection:

    This step connects to the database, and tells DBD::mysql to auto-convert to/from UTF-8.

    IMPORTANT: This requires a version of DBD::mysql greater than version 4

    use DBI(); my $dbh = DBI->connect ('dbi:mysql:test_db', $username, $password, {mysql_enable_utf8 => 1} );
  4. Write to and read from the DB:

    $dbh->do('INSERT INTO test_db.test VALUES(?)', $utf8_string); $dbh->do('SELECT string FROM test_db.test LIMIT 1'); my $new_string = $dbh->fetchrow_arrayref->[0];
  5. Display the retrieved string:

    The output data needs to be converted from Perl's internal format into a string of bytes that the console will understand.

    • on a UTF-8 console:
      use Encode qw( encode_utf8 ); print Encode::encode_utf8($new_string); OR # Add an auto-encoding layer binmode (STDIN,':utf8'); print $new_string;
    • or, on an ISO-8859-1 console:
      use Encode qw( encode ); print Encode::encode('ISO-8859-1', $new_string);
For more info, see perlunitut: Unicode in Perl, perluniintro, perlunicode, perlrun, binmode, open and PerlIO.

UPDATE - Added readmore tags. Added diagram illustrating round trip

UPDATE - Corrected a type: TO utf8, not from utf8