Darryl Gove's blog
Internationalising a perl program
I have a number of useful perl scripts, they all have English messages, and to be friendly need to be internationalised (or internationalized, depending on your locale). Fortunately, there's a perl module called Maketext which appears to do exactly what I need. In fact it seems to be deceptively simple, compared to the horror described in this article. Here's an example program:
$ more test.pl
#!/bin/perl -w
printf ("%i of %i optimised\n",1,7);
To make the internationalisation happen the print statements need to be converted into calls to maketext. Maketext has a slightly different syntax since the order that the parameters are written depends on the language that they are written in. The converted version of the code looks like:
$ more test.pl
#!/bin/perl -w
use Test::L10N;
my $lang = Test::L10N->get_handle() || die "Language support error";
print $lang->maketext("[_1] of [_2] optimised\n",1,7);
Rather than use the above version of the code, the behaviour of which will depend on the locale that it's run in, I'll modify it to assume that it's run in a US English locale.
$ more test.pl
#!/bin/perl -w
use Test::L10N;
my $lang = Test::L10N->get_handle('en_us') || die "Language support error";
print $lang->maketext("[_1] of [_2] optimised\n",1,7);
The code now makes use of a perl module, called L10N.pm that is specific for my "Test" program. This module needs to be created in a Test subdirectory, and the module basically exists to include the Maketext module from the Locale package:
$ more Test/L10N.pm package Test::L10N; use base qw(Locale::Maketext); 1;
For English locales, we'll default to keeping the original phrase as the output phrase.
$ more Test/L10N/en.pm
package Test::L10N::en;
use base qw(Test::L10N);
%Lexicon=('_AUTO'=>1,);
1;
If we want to translate the message into US English, then we add a en_us.pm file:
$ more Test/L10N/en_us.pm
package Test::L10N::en_us;
use base qw(Test::L10N);
%Lexicon=("[_1] of [_2] optimised\n"=>"[_1] of [_2] optimized\n",);
1;
The output of the program is 1 of 7 optimized rather than 1 of 7 optimised. Much clearer.
Posted at 12:58PM Jan 09, 2008 by Darryl Gove in Sun |


