Satch Satch - 1 month ago 7
Perl Question

Replace variables extracted from database with theirs values

I'd like to translate a perl web site in several languages. I search for and tried many ideas, but I think the best one is to save all translations inside the mySQL database. But I get a problem...

When a sentence extracted from the database contains a variable (scalar), it prints on the web page as a scalar:

You have $number new messages.


Is there a proper way to reassign
$number
its actual value ?

Thank you for your help !

Answer

You can use printf format strings in your database and pass in values to that. printf allows you to specify the position of the argument so only have know what position with the list of parameters "$number" is.

For example

#!/usr/bin/perl

use strict;

my $Details = {
   'Name' => 'Mr Satch',
   'Age'  => '31',
   'LocationEn' => 'England',
   'LocationFr' => 'Angleterre',
   'NewMessages' => 20,
   'OldMessages' => 120,
};

my $English = q(
 Hello %1$s, I see you are %2$s years old and from %3$s
 How are you today?
 You have %5$i new messages and %6$i old messages
 Have a nice day
);
my $French = q{
 Bonjour %1$s, je vous vois d'%4$s et âgés de %2$s ans.
 Comment allez-vous aujourd'hui?
 Vous avez %5$i nouveaux messages et %6$i anciens messages.
 Bonne journée.
};
printf($English, @$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});
printf($French,  @$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});

This would be a nightmare to maintain so an alternative might be to include an argument list in the database:

#!/usr/bin/perl

use strict;

sub fetch_row {
   return { 
      'Format' => 'You have %i new messages and %i old messages' . "\n",
      'Arguments'  => 'NewMessages OldMessages',
   }
}

sub PrintMessage {
    my ($info,$row) = @_;
    printf($row->{'Format'},@$info{split(/ +/,$row->{'Arguments'})});
}

my $Details = {
   'Name' => 'Mr Satch',
   'Age'  => '31',
   'LocationEn' => 'England',
   'LocationFr' => 'Angleterre',
   'NewMessages' => 20,
   'OldMessages' => 120,
};

my $row = fetch_row();
PrintMessage($Details,$row)
Comments