cdherold has asked for the wisdom of the Perl Monks concerning the following question:

Dearest Monks,

How does one make it so that when variables in a MySQL cell are read into an html document they are interpreted instead of taken literally.

For instance,assume that $type_of_animal = giraffe. If the MySQL cell that contained the text 'I wish I were a $type_of_animal' were selected and posted as html it would print 'I wish I were a $type_of_animal', even though $type_of_animal had been defined earlier in the perl script.

How do I get the script to interpret the variable read from the database so that it will print out 'I wish I were a giraffe'?

thanks,

Chris Herold

  • Comment on Interpreting variables pulled from MySQL

Replies are listed 'Best First'.
Re: Interpreting variables pulled from MySQL
by Errto (Vicar) on Jan 30, 2005 at 21:42 UTC

    If I understand you correctly, you are saying that in your MySQL table there are some rows with character data, and included in that character data are the names of variables, which you wish to substitue for at runtime. The easiest way to do this is eval, but please don't use it because it is extremely dangerous. Instead, you should keep the variables you want to substitue for not as Perl variables, but as entries in a hash. So for example, earlier in your program you might have code like

    my %table; $table{type_of_animal} = "giraffe";
    then you would do the substitution as something like
    my $row = $sth->fetchrow_arrayref; $row->[0] =~ s/\$(\w+)/exists $table{$1} ? $table{$1} : "\$$1"/eg;
    If you really must use variables instead of a hash, then do it with symbolic references:
    { no strict 'refs'; my $row = $sth->fetchrow_arrayref; $row->[0] =~ s/\$(\w+)/$$1/eg; }
    But then remember that your variable needs to be a global, not a lexical, in that case. Either of these ways is definitely better than eval, though.

    Update: Actually, if you use sh1tn's method I think the eval is safe. But otherwise it is not.

Re: Interpreting variables pulled from MySQL
by sh1tn (Priest) on Jan 30, 2005 at 21:31 UTC
    Is it possible for you to use 'eval' ?

    $sql_res = 'I wish I were a $type_of_animal'; $sql_res =~ s/(\$\w+)/eval$1/ge;
Re: Interpreting variables pulled from MySQL
by ZlR (Chaplain) on Jan 30, 2005 at 21:38 UTC
    Hello,

    I use the following line to achieve this goal :

    $ValCmd = eval qq("$ValCmdEx") ;
    This expands all the variables contained in the string ValCmdEx .

    These vars should all be correctly set before this command, or $ValCmd will be undef. So when I do this, I usually test afterwards that I get a coherent result

    ZlR.

Re: Interpreting variables pulled from MySQL
by borisz (Canon) on Jan 30, 2005 at 21:48 UTC
    Sounds you ask for eval.
    my $type_of_animal = 'giraffe'; my $text = 'I wish I were a $type_of_animal'; my $new_text = eval "qq{$text}";
    Boris