Next | Tricks of the Wizards | 45 |
This is a pretty big spell.
You have a hashful of variables, %VARS
You want to eval some code, and you want the environment for the eval to be the variables defined by the hash.
For example, many templating modules need to do this
my %VARS = ( cust_id => 666, items => ['fish', 'dog', 'carrot']; amount => 142857.33, );
my $template = <<'EOM'; # Or read it from a file
$name = db_lookup('NAME', $cust_id); $title = db_lookup('TITLE', $cust_id); $n = @items; $items = $n == 1 ? "item" : "$n_items items";
return "Dear $title $name, You still owe me \$$amount for the following $items: @items\n"; EOM my $result = my_eval($template, \%VARS);
# Result: # Dear Mr. Gates, # You still owe me $142857.33 for the following 3 items: # fish dog carrot
Note: $cust_id, @items, and $amount implicitly defined by the hash
Note: $name, $title, $n, and $items_list don't `leak out'
Next | Copyright © 2003 M. J. Dominus |