in reply to Interpolation of variables read from a file

Basically, you want a templating system. If you want to keep using the Perl hash syntax, I recommend the following approach:

my %act1 = ( "food" => "eat it", "drink" => "drink it", "Perl" => "play it"); my %act2 = ( "food" => "prepare it", "drink" => "be drunk", "Perl" => "write it"); my %actions = ( act1 => \%act1, act2 => \%act2, ); my %vars = ( item => \$item, ); my $out = '-p $act1{$item} -p $act2{$item} -p ... '; # resp. read that one from a file # The world's simpled templating system: $out =~ s-\$(\w+) # the name of the hash (%act1) \{ # opening brace \$(\w+) # the name of the variable to be used ($item) \} # closing brace - { my $useritem = $vars{ $2 }; $actions{$1}{$useritem} }gxe;

I haven't tested the code, so likely there are some syntax errors and errors with the specification of the regular expression - I hope that the comments help you enough to fix these.

Replies are listed 'Best First'.
Re^2: Interpolation of variables read from a file
by phio (Acolyte) on Dec 04, 2007 at 10:09 UTC
    I think Corion's method is more suitable for me :-)

    But I find a "bad" way to make it, and I think this way is more efficient in mem and time :-(

    File: main.pl => the main source file
    require "all_hashes.pl"; # read in all the hashes our $item = "Perl"; # this $item must be global :-( require "template.pl"; # perl interpolates all the variable print $out; # $out is defined in template.pl #...
    File: template.pl
    my $out = "-p $act1{$item} -p $act2{$item} ...";
    File: all_hashes.pl => the file contains all the hashes
    my %act1 = ( "food" => "eat it", "drink" => "drink it", "Perl" => "play it"); my %act2 = ( "food" => "prepare it", "drink" => "be drunk", "Perl" => "write it"); #...
    It's bad, hardcoded and has many global variables, however, a simple and fast way :-(