Next Tricks of the Wizards 45

A Templating System

        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


Next Copyright © 2003 M. J. Dominus