in reply to utf-8 problem

I offer some straight-forward code. Nothing really fancy and no Perl modules needed. This is a translation problem which screams hash table and look-up.
#!/usr/bin/perl -w use strict; #this is just a tricky way to make a hash table # #translate something to something screams hash #table - we can get this from a file or wherever, #or just make a %TranslateTable declaration statement.. # #I didn't think that was the point here... my %TranslateTable = map { my ($char, $hmtl) = split} split /\n/, <<'END'; Á &Aacute á &aacute É &Eacute é &eacute Í &Iacute í &iacute Ñ &Ntilde ñ &ntilde Ó &Oacute ó &oacute Ú &Uacute ú &uacute Ü &Uuml ü &uuml ¿ &iquest ¡ &iexcl END my $s = "El supersÁnico de los Indi "; my $xlated = fix_utf8($s); print "$s\n"; print "****translated = $xlated\n"; ## this can be done in fewer lines, and could be faster, ## but I didn't think that was the point either.... ## ## this is simple and straightforward. ## maybe I misunderstood the problem, but even so ## there maybe something that you can use ## sorry, that I don't speak this language, perhaps ## there is a funny goof, if so laugh! OK! sub fix_utf8 { my $in_string = shift; my $newstring =""; foreach my $char (split (//,$in_string) ) { $char = $TranslateTable{$char} if $TranslateTable{$char}; $newstring .= $char; } return $newstring; } __END__ ######### prints El supersÁnico de los Indi ****translated = El supers&Aacutenico de los Indi
Update: hash table gen is easier than first posted.
#!/usr/bin/perl -w use strict; #in this case hash table is easy #to generate...easier than first code.. my %TranslateTable = qw ( Á &Aacute á &aacute É &Eacute é &eacute Í &Iacute í &iacute Ñ &Ntilde ñ &ntilde Ó &Oacute ó &oacute Ú &Uacute ú &uacute Ü &Uuml ü &uuml ¿ &iquest ¡ &iexcl ); my $s = "El supersÁnico de los Indi "; my $xlated = fix_utf8($s); print "$s\n"; print "****translated = $xlated\n"; sub fix_utf8 { my $in_string = shift; my $newstring =""; foreach my $char (split (//,$in_string) ) { $char = $TranslateTable{$char} if $TranslateTable{$char}; $newstring .= $char; } return $newstring; } __END__ ######### prints El supersÁnico de los Indi ****translated = El supers&Aacutenico de los Indi

Replies are listed 'Best First'.
Re^2: utf-8 problem
by ikegami (Patriarch) on Jan 30, 2009 at 15:26 UTC
    map { my ($char, $hmtl) = split} split /\n/, <<'END';

    is the same as

    split ' ', <<'END';
      Quite correct! Even easier is just %table = qw( a value_a b value_b);. I amended my post. I'm not an HTML guy and I suspect that some other escape chars are needed around the translation. But hopefully the combined hints here will help this guy get going!