<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># -*- perl -*-
# Text::Template.pm
#
# Fill in `templates'
#
# Copyright 2013 M. J. Dominus.
# You may copy and distribute this program under the
# same terms as Perl itself.
# If in doubt, write to mjd-perl-template+@plover.com for a license.
#
# Version 1.46

package Text::Template;
require 5.004;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(fill_in_file fill_in_string TTerror);
use vars '$ERROR';
use strict;

$Text::Template::VERSION = '1.46';
my %GLOBAL_PREPEND = ('Text::Template' =&gt; '');

sub Version {
  $Text::Template::VERSION;
}

sub _param {
  my $kk;
  my ($k, %h) = @_;
  for $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") {
    return $h{$kk} if exists $h{$kk};
  }
  return;
}

sub always_prepend
{
  my $pack = shift;
  my $old = $GLOBAL_PREPEND{$pack};
  $GLOBAL_PREPEND{$pack} = shift;
  $old;
}

{
  my %LEGAL_TYPE;
  BEGIN { 
    %LEGAL_TYPE = map {$_=&gt;1} qw(FILE FILEHANDLE STRING ARRAY);
  }
  sub new {
    my $pack = shift;
    my %a = @_;
    my $stype = uc(_param('type', %a) || "FILE");
    my $source = _param('source', %a);
    my $untaint = _param('untaint', %a);
    my $prepend = _param('prepend', %a);
    my $alt_delim = _param('delimiters', %a);
    my $broken = _param('broken', %a);
    unless (defined $source) {
      require Carp;
      Carp::croak("Usage: $ {pack}::new(TYPE =&gt; ..., SOURCE =&gt; ...)");
    }
    unless ($LEGAL_TYPE{$stype}) {
      require Carp;
      Carp::croak("Illegal value `$stype' for TYPE parameter");
    }
    my $self = {TYPE =&gt; $stype,
		PREPEND =&gt; $prepend,
                UNTAINT =&gt; $untaint,
                BROKEN =&gt; $broken,
		(defined $alt_delim ? (DELIM =&gt; $alt_delim) : ()),
	       };
    # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken
    # are tainted, all the others become tainted too as a result of
    # sharing the expression with them.  We install $source separately
    # to prevent it from acquiring a spurious taint.
    $self-&gt;{SOURCE} = $source;

    bless $self =&gt; $pack;
    return unless $self-&gt;_acquire_data;
    
    $self;
  }
}

# Convert template objects of various types to type STRING,
# in which the template data is embedded in the object itself.
sub _acquire_data {
  my ($self) = @_;
  my $type = $self-&gt;{TYPE};
  if ($type eq 'STRING') {
    # nothing necessary    
  } elsif ($type eq 'FILE') {
    my $data = _load_text($self-&gt;{SOURCE});
    unless (defined $data) {
      # _load_text already set $ERROR
      return undef;
    }
    if ($self-&gt;{UNTAINT} &amp;&amp; _is_clean($self-&gt;{SOURCE})) {
      _unconditionally_untaint($data);
    }
    $self-&gt;{TYPE} = 'STRING';
    $self-&gt;{FILENAME} = $self-&gt;{SOURCE};
    $self-&gt;{SOURCE} = $data;
  } elsif ($type eq 'ARRAY') {
    $self-&gt;{TYPE} = 'STRING';
    $self-&gt;{SOURCE} = join '', @{$self-&gt;{SOURCE}};
  } elsif ($type eq 'FILEHANDLE') {
    $self-&gt;{TYPE} = 'STRING';
    local $/;
    my $fh = $self-&gt;{SOURCE};
    my $data = &lt;$fh&gt;; # Extra assignment avoids bug in Solaris perl5.00[45].
    if ($self-&gt;{UNTAINT}) {
      _unconditionally_untaint($data);
    }
    $self-&gt;{SOURCE} = $data;
  } else {
    # This should have been caught long ago, so it represents a 
    # drastic `can't-happen' sort of failure
    my $pack = ref $self;
    die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting";
  }
  $self-&gt;{DATA_ACQUIRED} = 1;
}

sub source {
  my ($self) = @_;
  $self-&gt;_acquire_data unless $self-&gt;{DATA_ACQUIRED};
  return $self-&gt;{SOURCE};
}

sub set_source_data {
  my ($self, $newdata) = @_;
  $self-&gt;{SOURCE} = $newdata;
  $self-&gt;{DATA_ACQUIRED} = 1;
  $self-&gt;{TYPE} = 'STRING';
  1;
}

sub compile {
  my $self = shift;

  return 1 if $self-&gt;{TYPE} eq 'PREPARSED';

  return undef unless $self-&gt;_acquire_data;
  unless ($self-&gt;{TYPE} eq 'STRING') {
    my $pack = ref $self;
    # This should have been caught long ago, so it represents a 
    # drastic `can't-happen' sort of failure
    die "Can only compile $pack objects of subtype STRING, but this is $self-&gt;{TYPE}; aborting";
  }

  my @tokens;
  my $delim_pats = shift() || $self-&gt;{DELIM};

  

  my ($t_open, $t_close) = ('{', '}');
  my $DELIM;			# Regex matches a delimiter if $delim_pats
  if (defined $delim_pats) {
    ($t_open, $t_close) = @$delim_pats;
    $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))";
    @tokens = split /($DELIM|\n)/, $self-&gt;{SOURCE};
  } else {
    @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self-&gt;{SOURCE};
  }
  my $state = 'TEXT';
  my $depth = 0;
  my $lineno = 1;
  my @content;
  my $cur_item = '';
  my $prog_start;
  while (@tokens) {
    my $t = shift @tokens;
    next if $t eq '';
    if ($t eq $t_open) {	# Brace or other opening delimiter
      if ($depth == 0) {
	push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
	$cur_item = '';
	$state = 'PROG';
	$prog_start = $lineno;
      } else {
	$cur_item .= $t;
      }
      $depth++;
    } elsif ($t eq $t_close) {	# Brace or other closing delimiter
      $depth--;
      if ($depth &lt; 0) {
	$ERROR = "Unmatched close brace at line $lineno";
	return undef;
      } elsif ($depth == 0) {
	push @content, [$state, $cur_item, $prog_start] if $cur_item ne '';
	$state = 'TEXT';
	$cur_item = '';
      } else {
	$cur_item .= $t;
      }
    } elsif (!$delim_pats &amp;&amp; $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\}
      $cur_item .= '\\';
    } elsif (!$delim_pats &amp;&amp; $t =~ /^\\([{}])$/) { # Escaped (literal) brace?
	$cur_item .= $1;
    } elsif ($t eq "\n") {	# Newline
      $lineno++;
      $cur_item .= $t;
    } else {			# Anything else
      $cur_item .= $t;
    }
  }

  if ($state eq 'PROG') {
    $ERROR = "End of data inside program text that began at line $prog_start";
    return undef;
  } elsif ($state eq 'TEXT') {
    push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
  } else {
    die "Can't happen error #1";
  }
  
  $self-&gt;{TYPE} = 'PREPARSED';
  $self-&gt;{SOURCE} = \@content;
  1;
}

sub prepend_text {
  my ($self) = @_;
  my $t = $self-&gt;{PREPEND};
  unless (defined $t) {
    $t = $GLOBAL_PREPEND{ref $self};
    unless (defined $t) {
      $t = $GLOBAL_PREPEND{'Text::Template'};
    }
  }
  $self-&gt;{PREPEND} = $_[1] if $#_ &gt;= 1;
  return $t;
}

sub fill_in {
  my $fi_self = shift;
  my %fi_a = @_;

  unless ($fi_self-&gt;{TYPE} eq 'PREPARSED') {
    my $delims = _param('delimiters', %fi_a);
    my @delim_arg = (defined $delims ? ($delims) : ());
    $fi_self-&gt;compile(@delim_arg)
      or return undef;
  }

  my $fi_varhash = _param('hash', %fi_a);
  my $fi_package = _param('package', %fi_a) ;
  my $fi_broken  = 
    _param('broken', %fi_a)  || $fi_self-&gt;{BROKEN} || \&amp;_default_broken;
  my $fi_broken_arg = _param('broken_arg', %fi_a) || [];
  my $fi_safe = _param('safe', %fi_a);
  my $fi_ofh = _param('output', %fi_a);
  my $fi_eval_package;
  my $fi_scrub_package = 0;
  my $fi_filename = _param('filename') || $fi_self-&gt;{FILENAME} || 'template';

  my $fi_prepend = _param('prepend', %fi_a);
  unless (defined $fi_prepend) {
    $fi_prepend = $fi_self-&gt;prepend_text;
  }

  if (defined $fi_safe) {
    $fi_eval_package = 'main';
  } elsif (defined $fi_package) {
    $fi_eval_package = $fi_package;
  } elsif (defined $fi_varhash) {
    $fi_eval_package = _gensym();
    $fi_scrub_package = 1;
  } else {
    $fi_eval_package = caller;
  }

  my $fi_install_package;
  if (defined $fi_varhash) {
    if (defined $fi_package) {
      $fi_install_package = $fi_package;
    } elsif (defined $fi_safe) {
      $fi_install_package = $fi_safe-&gt;root;
    } else {
      $fi_install_package = $fi_eval_package; # The gensymmed one
    }
    _install_hash($fi_varhash =&gt; $fi_install_package);
  }

  if (defined $fi_package &amp;&amp; defined $fi_safe) {
    no strict 'refs';
    # Big fat magic here: Fix it so that the user-specified package
    # is the default one available in the safe compartment.
    *{$fi_safe-&gt;root . '::'} = \%{$fi_package . '::'};   # LOD
  }

  my $fi_r = '';
  my $fi_item;
  foreach $fi_item (@{$fi_self-&gt;{SOURCE}}) {
    my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
    if ($fi_type eq 'TEXT') {
      $fi_self-&gt;append_text_to_output(
        text   =&gt; $fi_text,
        handle =&gt; $fi_ofh,
        out    =&gt; \$fi_r,
        type   =&gt; $fi_type,
      );
    } elsif ($fi_type eq 'PROG') {
      no strict;
      my $fi_lcomment = "#line $fi_lineno $fi_filename";
      my $fi_progtext = 
        "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;";
      my $fi_res;
      my $fi_eval_err = '';
      if ($fi_safe) {
        $fi_safe-&gt;reval(q{undef $OUT});
	$fi_res = $fi_safe-&gt;reval($fi_progtext);
	$fi_eval_err = $@;
	my $OUT = $fi_safe-&gt;reval('$OUT');
	$fi_res = $OUT if defined $OUT;
      } else {
	my $OUT;
	$fi_res = eval $fi_progtext;
	$fi_eval_err = $@;
	$fi_res = $OUT if defined $OUT;
      }

      # If the value of the filled-in text really was undef,
      # change it to an explicit empty string to avoid undefined
      # value warnings later.
      $fi_res = '' unless defined $fi_res;

      if ($fi_eval_err) {
	$fi_res = $fi_broken-&gt;(text =&gt; $fi_text,
			       error =&gt; $fi_eval_err,
			       lineno =&gt; $fi_lineno,
			       arg =&gt; $fi_broken_arg,
			       );
	if (defined $fi_res) {
          $fi_self-&gt;append_text_to_output(
            text   =&gt; $fi_res,
            handle =&gt; $fi_ofh,
            out    =&gt; \$fi_r,
            type   =&gt; $fi_type,
          );
	} else {
	  return $fi_res;		# Undefined means abort processing
	}
      } else {
        $fi_self-&gt;append_text_to_output(
          text   =&gt; $fi_res,
          handle =&gt; $fi_ofh,
          out    =&gt; \$fi_r,
          type   =&gt; $fi_type,
        );
      }
    } else {
      die "Can't happen error #2";
    }
  }

  _scrubpkg($fi_eval_package) if $fi_scrub_package;
  defined $fi_ofh ? 1 : $fi_r;
}

sub append_text_to_output {
  my ($self, %arg) = @_;

  if (defined $arg{handle}) {
    print { $arg{handle} } $arg{text};
  } else {
    ${ $arg{out} } .= $arg{text};
  }

  return;
}

sub fill_this_in {
  my $pack = shift;
  my $text = shift;
  my $templ = $pack-&gt;new(TYPE =&gt; 'STRING', SOURCE =&gt; $text, @_)
    or return undef;
  $templ-&gt;compile or return undef;
  my $result = $templ-&gt;fill_in(@_);
  $result;
}

sub fill_in_string {
  my $string = shift;
  my $package = _param('package', @_);
  push @_, 'package' =&gt; scalar(caller) unless defined $package;
  Text::Template-&gt;fill_this_in($string, @_);
}

sub fill_in_file {
  my $fn = shift;
  my $templ = Text::Template-&gt;new(TYPE =&gt; 'FILE', SOURCE =&gt; $fn, @_)
    or return undef;
  $templ-&gt;compile or return undef;
  my $text = $templ-&gt;fill_in(@_);
  $text;
}

sub _default_broken {
  my %a = @_;
  my $prog_text = $a{text};
  my $err = $a{error};
  my $lineno = $a{lineno};
  chomp $err;
#  $err =~ s/\s+at .*//s;
  "Program fragment delivered error ``$err''";
}

sub _load_text {
  my $fn = shift;
  local *F;
  unless (open F, $fn) {
    $ERROR = "Couldn't open file $fn: $!";
    return undef;
  }
  local $/;
  &lt;F&gt;;
}

sub _is_clean {
  my $z;
  eval { ($z = join('', @_)), eval '#' . substr($z,0,0); 1 }   # LOD
}

sub _unconditionally_untaint {
  for (@_) {
    ($_) = /(.*)/s;
  }
}

{
  my $seqno = 0;
  sub _gensym {
    __PACKAGE__ . '::GEN' . $seqno++;
  }
  sub _scrubpkg {
    my $s = shift;
    $s =~ s/^Text::Template:://;
    no strict 'refs';
    my $hash = $Text::Template::{$s."::"};
    foreach my $key (keys %$hash) {
      undef $hash-&gt;{$key};
    }
    %$hash = ();
    delete $Text::Template::{$s."::"};
  }
}
  
# Given a hashful of variables (or a list of such hashes)
# install the variables into the specified package,
# overwriting whatever variables were there before.
sub _install_hash {
  my $hashlist = shift;
  my $dest = shift;
  if (UNIVERSAL::isa($hashlist, 'HASH')) {
    $hashlist = [$hashlist];
  }
  my $hash;
  foreach $hash (@$hashlist) {
    my $name;
    foreach $name (keys %$hash) {
      my $val = $hash-&gt;{$name};
      no strict 'refs';
      local *SYM = *{"$ {dest}::$name"};
      if (! defined $val) {
	delete ${"$ {dest}::"}{$name};
      } elsif (ref $val) {
	*SYM = $val;
      } else {
 	*SYM = \$val;
      }
    }
  }
}

sub TTerror { $ERROR }

1;


=head1 NAME 

Text::Template - Expand template text with embedded Perl

=head1 VERSION

This file documents C&lt;Text::Template&gt; version B&lt;1.46&gt;

=head1 SYNOPSIS

 use Text::Template;


 $template = Text::Template-&gt;new(TYPE =&gt; 'FILE',  SOURCE =&gt; 'filename.tmpl');
 $template = Text::Template-&gt;new(TYPE =&gt; 'ARRAY', SOURCE =&gt; [ ... ] );
 $template = Text::Template-&gt;new(TYPE =&gt; 'FILEHANDLE', SOURCE =&gt; $fh );
 $template = Text::Template-&gt;new(TYPE =&gt; 'STRING', SOURCE =&gt; '...' );
 $template = Text::Template-&gt;new(PREPEND =&gt; q{use strict;}, ...);

 # Use a different template file syntax:
 $template = Text::Template-&gt;new(DELIMITERS =&gt; [$open, $close], ...);

 $recipient = 'King';
 $text = $template-&gt;fill_in();  # Replaces `{$recipient}' with `King'
 print $text;

 $T::recipient = 'Josh';
 $text = $template-&gt;fill_in(PACKAGE =&gt; T);

 # Pass many variables explicitly
 $hash = { recipient =&gt; 'Abed-Nego',
           friends =&gt; [ 'me', 'you' ],
           enemies =&gt; { loathsome =&gt; 'Bill Gates',
                        fearsome =&gt; 'Larry Ellison' },
         };
 $text = $template-&gt;fill_in(HASH =&gt; $hash, ...);
 # $recipient is Abed-Nego,
 # @friends is ( 'me', 'you' ),
 # %enemies is ( loathsome =&gt; ..., fearsome =&gt; ... )


 # Call &amp;callback in case of programming errors in template
 $text = $template-&gt;fill_in(BROKEN =&gt; \&amp;callback, BROKEN_ARG =&gt; $ref, ...);

 # Evaluate program fragments in Safe compartment with restricted permissions
 $text = $template-&gt;fill_in(SAFE =&gt; $compartment, ...);

 # Print result text instead of returning it
 $success = $template-&gt;fill_in(OUTPUT =&gt; \*FILEHANDLE, ...);

 # Parse template with different template file syntax:
 $text = $template-&gt;fill_in(DELIMITERS =&gt; [$open, $close], ...);
 # Note that this is *faster* than using the default delimiters

 # Prepend specified perl code to each fragment before evaluating:
 $text = $template-&gt;fill_in(PREPEND =&gt; q{use strict 'vars';}, ...);

 use Text::Template 'fill_in_string';
 $text = fill_in_string( &lt;&lt;EOM, PACKAGE =&gt; 'T', ...);
 Dear {$recipient},
 Pay me at once.
        Love, 
         G.V.
 EOM

 use Text::Template 'fill_in_file';
 $text = fill_in_file($filename, ...);

 # All templates will always have `use strict vars' attached to all fragments
 Text::Template-&gt;always_prepend(q{use strict 'vars';});

=head1 DESCRIPTION

This is a library for generating form letters, building HTML pages, or
filling in templates generally.  A `template' is a piece of text that
has little Perl programs embedded in it here and there.  When you
`fill in' a template, you evaluate the little programs and replace
them with their values.  

You can store a template in a file outside your program.  People can
modify the template without modifying the program.  You can separate
the formatting details from the main code, and put the formatting
parts of the program into the template.  That prevents code bloat and
encourages functional separation.

=head2 Example

Here's an example of a template, which we'll suppose is stored in the
file C&lt;formletter.tmpl&gt;:

	Dear {$title} {$lastname},

	It has come to our attention that you are delinquent in your
	{$monthname[$last_paid_month]} payment.  Please remit
	${sprintf("%.2f", $amount)} immediately, or your patellae may
	be needlessly endangered.

			Love,

			Mark "Vizopteryx" Dominus


The result of filling in this template is a string, which might look
something like this:

	Dear Mr. Gates,

	It has come to our attention that you are delinquent in your
	February payment.  Please remit
	$392.12 immediately, or your patellae may
	be needlessly endangered.


			Love,

			Mark "Vizopteryx" Dominus

Here is a complete program that transforms the example
template into the example result, and prints it out:

	use Text::Template;

	my $template = Text::Template-&gt;new(SOURCE =&gt; 'formletter.tmpl')
	  or die "Couldn't construct template: $Text::Template::ERROR";

	my @monthname = qw(January February March April May June
                           July August September October November December);
	my %vars = (title =&gt; 'Mr.',
		    firstname =&gt; 'Bill',
		    lastname =&gt; 'Gates',
		    last_paid_month =&gt; 1,   # February
		    amount =&gt; 392.12,
		    monthname =&gt; \@monthname,
		   );

	my $result = $template-&gt;fill_in(HASH =&gt; \%vars);

	if (defined $result) { print $result }
	else { die "Couldn't fill in template: $Text::Template::ERROR" }


=head2 Philosophy

When people make a template module like this one, they almost always
start by inventing a special syntax for substitutions.  For example,
they build it so that a string like C&lt;%%VAR%%&gt; is replaced with the
value of C&lt;$VAR&gt;.  Then they realize the need extra formatting, so
they put in some special syntax for formatting.  Then they need a
loop, so they invent a loop syntax.  Pretty soon they have a new
little template language.

This approach has two problems: First, their little language is
crippled. If you need to do something the author hasn't thought of,
you lose.  Second: Who wants to learn another language?  You already
know Perl, so why not use it?

C&lt;Text::Template&gt; templates are programmed in I&lt;Perl&gt;.  You embed Perl
code in your template, with C&lt;{&gt; at the beginning and C&lt;}&gt; at the end.
If you want a variable interpolated, you write it the way you would in
Perl.  If you need to make a loop, you can use any of the Perl loop
constructions.  All the Perl built-in functions are available.

=head1 Details

=head2 Template Parsing

The C&lt;Text::Template&gt; module scans the template source.  An open brace
C&lt;{&gt; begins a program fragment, which continues until the matching
close brace C&lt;}&gt;.  When the template is filled in, the program
fragments are evaluated, and each one is replaced with the resulting
value to yield the text that is returned.

A backslash C&lt;\&gt; in front of a brace (or another backslash that is in
front of a brace) escapes its special meaning.  The result of filling
out this template:

	\{ The sum of 1 and 2 is {1+2}  \}

is

	{ The sum of 1 and 2 is 3  }

If you have an unmatched brace, C&lt;Text::Template&gt; will return a
failure code and a warning about where the problem is.  Backslashes
that do not precede a brace are passed through unchanged.  If you have
a template like this:

	{ "String that ends in a newline.\n" }

The backslash inside the string is passed through to Perl unchanged,
so the C&lt;\n&gt; really does turn into a newline.  See the note at the end
for details about the way backslashes work.  Backslash processing is
I&lt;not&gt; done when you specify alternative delimiters with the
C&lt;DELIMITERS&gt; option.  (See L&lt;"Alternative Delimiters"&gt;, below.)

Each program fragment should be a sequence of Perl statements, which
are evaluated the usual way.  The result of the last statement
executed will be evaluated in scalar context; the result of this
statement is a string, which is interpolated into the template in
place of the program fragment itself.

The fragments are evaluated in order, and side effects from earlier
fragments will persist into later fragments:

	{$x = @things; ''}The Lord High Chamberlain has gotten {$x}
	things for me this year.  
	{ $diff = $x - 17; 
	  $more = 'more'
	  if ($diff == 0) {
	    $diff = 'no';
	  } elsif ($diff &lt; 0) {
	    $more = 'fewer';
	  } 
          '';
	} 
	That is {$diff} {$more} than he gave me last year.

The value of C&lt;$x&gt; set in the first line will persist into the next
fragment that begins on the third line, and the values of C&lt;$diff&gt; and
C&lt;$more&gt; set in the second fragment will persist and be interpolated
into the last line.  The output will look something like this:

	The Lord High Chamberlain has gotten 42
	things for me this year.  

	That is 25 more than he gave me last year.

That is all the syntax there is.  

=head2 The C&lt;$OUT&gt; variable

There is one special trick you can play in a template.  Here is the
motivation for it:  Suppose you are going to pass an array, C&lt;@items&gt;,
into the template, and you want the template to generate a bulleted
list with a header, like this:

	Here is a list of the things I have got for you since 1907:
	  * Ivory
	  * Apes
	  * Peacocks
	  * ...

One way to do it is with a template like this:

	Here is a list of the things I have got for you since 1907:
	{ my $blist = '';
          foreach $i (@items) {
            $blist .= qq{  * $i\n};
          }    
          $blist;
        } 

Here we construct the list in a variable called C&lt;$blist&gt;, which we
return at the end.  This is a little cumbersome.  There is a shortcut.

Inside of templates, there is a special variable called C&lt;$OUT&gt;.
Anything you append to this variable will appear in the output of the
template.  Also, if you use C&lt;$OUT&gt; in a program fragment, the normal
behavior, of replacing the fragment with its return value, is
disabled; instead the fragment is replaced with the value of C&lt;$OUT&gt;.
This means that you can write the template above like this:

	Here is a list of the things I have got for you since 1907:
	{ foreach $i (@items) {
            $OUT .= "  * $i\n";
          }    
        } 

C&lt;$OUT&gt; is reinitialized to the empty string at the start of each
program fragment.  It is private to C&lt;Text::Template&gt;, so 
you can't use a variable named C&lt;$OUT&gt; in your template without
invoking the special behavior.

=head2 General Remarks

All C&lt;Text::Template&gt; functions return C&lt;undef&gt; on failure, and set the
variable C&lt;$Text::Template::ERROR&gt; to contain an explanation of what
went wrong.  For example, if you try to create a template from a file
that does not exist, C&lt;$Text::Template::ERROR&gt; will contain something like:

	Couldn't open file xyz.tmpl: No such file or directory

=head2 C&lt;new&gt;

	$template = new Text::Template ( TYPE =&gt; ..., SOURCE =&gt; ... );

This creates and returns a new template object.  C&lt;new&gt; returns
C&lt;undef&gt; and sets C&lt;$Text::Template::ERROR&gt; if it can't create the
template object.  C&lt;SOURCE&gt; says where the template source code will
come from.  C&lt;TYPE&gt; says what kind of object the source is.

The most common type of source is a file:

	new Text::Template ( TYPE =&gt; 'FILE', SOURCE =&gt; $filename );

This reads the template from the specified file.  The filename is
opened with the Perl C&lt;open&gt; command, so it can be a pipe or anything
else that makes sense with C&lt;open&gt;.

The C&lt;TYPE&gt; can also be C&lt;STRING&gt;, in which case the C&lt;SOURCE&gt; should
be a string:

	new Text::Template ( TYPE =&gt; 'STRING', 
                             SOURCE =&gt; "This is the actual template!" );

The C&lt;TYPE&gt; can be C&lt;ARRAY&gt;, in which case the source should be a
reference to an array of strings.  The concatenation of these strings
is the template:

	new Text::Template ( TYPE =&gt; 'ARRAY', 
                             SOURCE =&gt; [ "This is ", "the actual", 
                                         " template!",
                                       ]
                           );

The C&lt;TYPE&gt; can be FILEHANDLE, in which case the source should be an
open filehandle (such as you got from the C&lt;FileHandle&gt; or C&lt;IO::*&gt;
packages, or a glob, or a reference to a glob).  In this case
C&lt;Text::Template&gt; will read the text from the filehandle up to
end-of-file, and that text is the template:

	# Read template source code from STDIN:
	new Text::Template ( TYPE =&gt; 'FILEHANDLE', 
                             SOURCE =&gt; \*STDIN  );


If you omit the C&lt;TYPE&gt; attribute, it's taken to be C&lt;FILE&gt;.
C&lt;SOURCE&gt; is required.  If you omit it, the program will abort.

The words C&lt;TYPE&gt; and C&lt;SOURCE&gt; can be spelled any of the following ways:

	TYPE	SOURCE
	Type	Source
	type	source
	-TYPE	-SOURCE
	-Type	-Source
	-type	-source

Pick a style you like and stick with it.

=over 4

=item C&lt;DELIMITERS&gt;

You may also add a C&lt;DELIMITERS&gt; option.  If this option is present,
its value should be a reference to an array of two strings.  The first
string is the string that signals the beginning of each program
fragment, and the second string is the string that signals the end of
each program fragment.  See L&lt;"Alternative Delimiters"&gt;, below.

=item C&lt;UNTAINT&gt;

If your program is running in taint mode, you may have problems if
your templates are stored in files.  Data read from files is
considered 'untrustworthy', and taint mode will not allow you to
evaluate the Perl code in the file.  (It is afraid that a malicious
person might have tampered with the file.)

In some environments, however, local files are trustworthy.  You can
tell C&lt;Text::Template&gt; that a certain file is trustworthy by supplying
C&lt;UNTAINT =E&lt;gt&gt; 1&gt; in the call to C&lt;new&gt;.  This will tell
C&lt;Text::Template&gt; to disable taint checks on template code that has
come from a file, as long as the filename itself is considered
trustworthy.  It will also disable taint checks on template code that
comes from a filehandle.  When used with C&lt;TYPE =E&lt;gt&gt; 'string'&gt; or C&lt;TYPE
=E&lt;gt&gt; 'array'&gt;, it has no effect.

See L&lt;perlsec&gt; for more complete information about tainting.

Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr
for help with this feature.

=item C&lt;PREPEND&gt;

This option is passed along to the C&lt;fill_in&gt; call unless it is
overridden in the arguments to C&lt;fill_in&gt;.  See L&lt;C&lt;PREPEND&gt; feature
and using C&lt;strict&gt; in templates&gt; below.

=item C&lt;BROKEN&gt;

This option is passed along to the C&lt;fill_in&gt; call unless it is
overridden in the arguments to C&lt;fill_in&gt;.  See L&lt;C&lt;BROKEN&gt;&gt; below.

=back

=head2 C&lt;compile&gt;

	$template-&gt;compile()

Loads all the template text from the template's source, parses and
compiles it.  If successful, returns true; otherwise returns false and
sets C&lt;$Text::Template::ERROR&gt;.  If the template is already compiled,
it returns true and does nothing.  

You don't usually need to invoke this function, because C&lt;fill_in&gt;
(see below) compiles the template if it isn't compiled already.

If there is an argument to this function, it must be a reference to an
array containing alternative delimiter strings.  See C&lt;"Alternative
Delimiters"&gt;, below.

=head2 C&lt;fill_in&gt;

	$template-&gt;fill_in(OPTIONS);

Fills in a template.  Returns the resulting text if successful.
Otherwise, returns C&lt;undef&gt;  and sets C&lt;$Text::Template::ERROR&gt;.

The I&lt;OPTIONS&gt; are a hash, or a list of key-value pairs.  You can
write the key names in any of the six usual styles as above; this
means that where this manual says C&lt;PACKAGE&gt; (for example) you can
actually use any of

	PACKAGE Package package -PACKAGE -Package -package

Pick a style you like and stick with it.  The all-lowercase versions
may yield spurious warnings about

	Ambiguous use of package =&gt; resolved to "package"

so you might like to avoid them and use the capitalized versions.

At present, there are eight legal options:  C&lt;PACKAGE&gt;, C&lt;BROKEN&gt;,
C&lt;BROKEN_ARG&gt;, C&lt;SAFE&gt;, C&lt;HASH&gt;, C&lt;OUTPUT&gt;, and C&lt;DELIMITERS&gt;.

=over 4

=item C&lt;PACKAGE&gt;

C&lt;PACKAGE&gt; specifies the name of a package in which the program
fragments should be evaluated.  The default is to use the package from
which C&lt;fill_in&gt; was called.  For example, consider this template:

	The value of the variable x is {$x}.

If you use C&lt;$template-E&lt;gt&gt;fill_in(PACKAGE =E&lt;gt&gt; 'R')&gt; , then the C&lt;$x&gt; in
the template is actually replaced with the value of C&lt;$R::x&gt;.  If you
omit the C&lt;PACKAGE&gt; option, C&lt;$x&gt; will be replaced with the value of
the C&lt;$x&gt; variable in the package that actually called C&lt;fill_in&gt;.

You should almost always use C&lt;PACKAGE&gt;.  If you don't, and your
template makes changes to variables, those changes will be propagated
back into the main program.  Evaluating the template in a private
package helps prevent this.  The template can still modify variables
in your program if it wants to, but it will have to do so explicitly.
See the section at the end on `Security'.

Here's an example of using C&lt;PACKAGE&gt;:

	Your Royal Highness,

	Enclosed please find a list of things I have gotten
	for you since 1907:

	{ foreach $item (@items) {
            $item_no++;
	    $OUT .= " $item_no. \u$item\n";
	  }
	}

	Signed,
	Lord High Chamberlain

We want to pass in an array which will be assigned to the array
C&lt;@items&gt;.  Here's how to do that:


	@items = ('ivory', 'apes', 'peacocks', );
	$template-&gt;fill_in();

This is not very safe.  The reason this isn't as safe is that if you
had a variable named C&lt;$item_no&gt; in scope in your program at the point
you called C&lt;fill_in&gt;, its value would be clobbered by the act of
filling out the template.  The problem is the same as if you had
written a subroutine that used those variables in the same way that
the template does.  (C&lt;$OUT&gt; is special in templates and is always
safe.)

One solution to this is to make the C&lt;$item_no&gt; variable private to the
template by declaring it with C&lt;my&gt;.  If the template does this, you
are safe.

But if you use the C&lt;PACKAGE&gt; option, you will probably be safe even
if the template does I&lt;not&gt; declare its variables with C&lt;my&gt;:

	@Q::items = ('ivory', 'apes', 'peacocks', );
	$template-&gt;fill_in(PACKAGE =&gt; 'Q');

In this case the template will clobber the variable C&lt;$Q::item_no&gt;,
which is not related to the one your program was using.

Templates cannot affect variables in the main program that are
declared with C&lt;my&gt;, unless you give the template references to those
variables.

=item C&lt;HASH&gt;

You may not want to put the template variables into a package.
Packages can be hard to manage:  You can't copy them, for example.
C&lt;HASH&gt; provides an alternative.  

The value for C&lt;HASH&gt; should be a reference to a hash that maps
variable names to values.  For example, 

	$template-&gt;fill_in(HASH =&gt; { recipient =&gt; "The King",
				     items =&gt; ['gold', 'frankincense', 'myrrh'],
	                             object =&gt; \$self,
				   });

will fill out the template and use C&lt;"The King"&gt; as the value of
C&lt;$recipient&gt; and the list of items as the value of C&lt;@items&gt;.  Note
that we pass an array reference, but inside the template it appears as
an array.  In general, anything other than a simple string or number
should be passed by reference.

We also want to pass an object, which is in C&lt;$self&gt;; note that we
pass a reference to the object, C&lt;\$self&gt; instead.  Since we've passed
a reference to a scalar, inside the template the object appears as
C&lt;$object&gt;.  

The full details of how it works are a little involved, so you might
want to skip to the next section.

Suppose the key in the hash is I&lt;key&gt; and the value is I&lt;value&gt;.  

=over 4

=item *

If the I&lt;value&gt; is C&lt;undef&gt;, then any variables named C&lt;$key&gt;,
C&lt;@key&gt;, C&lt;%key&gt;, etc., are undefined.  

=item *

If the I&lt;value&gt; is a string or a number, then C&lt;$key&gt; is set to that
value in the template.

=item *

For anything else, you must pass a reference.

If the I&lt;value&gt; is a reference to an array, then C&lt;@key&gt; is set to
that array.  If the I&lt;value&gt; is a reference to a hash, then C&lt;%key&gt; is
set to that hash.  Similarly if I&lt;value&gt; is any other kind of
reference.  This means that

	var =&gt; "foo"

and

	var =&gt; \"foo"

have almost exactly the same effect.  (The difference is that in the
former case, the value is copied, and in the latter case it is
aliased.)  

=item *

In particular, if you want the template to get an object or any kind,
you must pass a reference to it:

	$template-&gt;fill_in(HASH =&gt; { database_handle =&gt; \$dbh, ... });

If you do this, the template will have a variable C&lt;$database_handle&gt;
which is the database handle object.  If you leave out the C&lt;\&gt;, the
template will have a hash C&lt;%database_handle&gt;, which exposes the
internal structure of the database handle object; you don't want that.

=back

Normally, the way this works is by allocating a private package,
loading all the variables into the package, and then filling out the
template as if you had specified that package.  A new package is
allocated each time.  However, if you I&lt;also&gt; use the C&lt;PACKAGE&gt;
option, C&lt;Text::Template&gt; loads the variables into the package you
specified, and they stay there after the call returns.  Subsequent
calls to C&lt;fill_in&gt; that use the same package will pick up the values
you loaded in.

If the argument of C&lt;HASH&gt; is a reference to an array instead of a
reference to a hash, then the array should contain a list of hashes
whose contents are loaded into the template package one after the
other.  You can use this feature if you want to combine several sets
of variables.  For example, one set of variables might be the defaults
for a fill-in form, and the second set might be the user inputs, which
override the defaults when they are present:

	$template-&gt;fill_in(HASH =&gt; [\%defaults, \%user_input]);

You can also use this to set two variables with the same name:

	$template-&gt;fill_in(HASH =&gt; [{ v =&gt; "The King" },
                                    { v =&gt; [1,2,3] },
	                           ]
                          );

This sets C&lt;$v&gt; to C&lt;"The King"&gt; and C&lt;@v&gt; to C&lt;(1,2,3)&gt;.	

=item C&lt;BROKEN&gt;

If any of the program fragments fails to compile or aborts for any
reason, and you have set the C&lt;BROKEN&gt; option to a function reference,
C&lt;Text::Template&gt; will invoke the function.  This function is called
the I&lt;C&lt;BROKEN&gt; function&gt;.  The C&lt;BROKEN&gt; function will tell
C&lt;Text::Template&gt; what to do next.  

If the C&lt;BROKEN&gt; function returns C&lt;undef&gt;, C&lt;Text::Template&gt; will
immediately abort processing the template and return the text that it
has accumulated so far.  If your function does this, it should set a
flag that you can examine after C&lt;fill_in&gt; returns so that you can
tell whether there was a premature return or not. 

If the C&lt;BROKEN&gt; function returns any other value, that value will be
interpolated into the template as if that value had been the return
value of the program fragment to begin with.  For example, if the
C&lt;BROKEN&gt; function returns an error string, the error string will be
interpolated into the output of the template in place of the program
fragment that cased the error.

If you don't specify a C&lt;BROKEN&gt; function, C&lt;Text::Template&gt; supplies
a default one that returns something like

	Program fragment delivered error ``Illegal division by 0 at
	template line 37''

(Note that the format of this message has changed slightly since
version 1.31.)  The return value of the C&lt;BROKEN&gt; function is
interpolated into the template at the place the error occurred, so
that this template:

	(3+4)*5 = { 3+4)*5 }

yields this result:

	(3+4)*5 = Program fragment delivered error ``syntax error at template line 1''

If you specify a value for the C&lt;BROKEN&gt; attribute, it should be a
reference to a function that C&lt;fill_in&gt; can call instead of the
default function.

C&lt;fill_in&gt; will pass a hash to the C&lt;broken&gt; function.
The hash will have at least these three members:

=over 4

=item C&lt;text&gt;

The source code of the program fragment that failed

=item C&lt;error&gt;

The text of the error message (C&lt;$@&gt;) generated by eval.

The text has been modified to omit the trailing newline and to include
the name of the template file (if there was one).  The line number
counts from the beginning of the template, not from the beginning of
the failed program fragment.

=item C&lt;lineno&gt;

The line number of the template at which the program fragment began.

=back

There may also be an C&lt;arg&gt; member.  See C&lt;BROKEN_ARG&gt;, below

=item C&lt;BROKEN_ARG&gt;

If you supply the C&lt;BROKEN_ARG&gt; option to C&lt;fill_in&gt;, the value of the
option is passed to the C&lt;BROKEN&gt; function whenever it is called.  The
default C&lt;BROKEN&gt; function ignores the C&lt;BROKEN_ARG&gt;, but you can
write a custom C&lt;BROKEN&gt; function that uses the C&lt;BROKEN_ARG&gt; to get
more information about what went wrong. 

The C&lt;BROKEN&gt; function could also use the C&lt;BROKEN_ARG&gt; as a reference
to store an error message or some other information that it wants to
communicate back to the caller.  For example:

	$error = '';

	sub my_broken {	
	   my %args = @_;
	   my $err_ref = $args{arg};
	   ...
	   $$err_ref = "Some error message";
	   return undef;
	}

	$template-&gt;fill_in(BROKEN =&gt; \&amp;my_broken,
			   BROKEN_ARG =&gt; \$error,
			  );

	if ($error) {
	  die "It didn't work: $error";
	}

If one of the program fragments in the template fails, it will call
the C&lt;BROKEN&gt; function, C&lt;my_broken&gt;, and pass it the C&lt;BROKEN_ARG&gt;,
which is a reference to C&lt;$error&gt;.  C&lt;my_broken&gt; can store an error
message into C&lt;$error&gt; this way.  Then the function that called
C&lt;fill_in&gt; can see if C&lt;my_broken&gt; has left an error message for it
to find, and proceed accordingly.

=item C&lt;SAFE&gt;

If you give C&lt;fill_in&gt; a C&lt;SAFE&gt; option, its value should be a safe
compartment object from the C&lt;Safe&gt; package.  All evaluation of
program fragments will be performed in this compartment.  See L&lt;Safe&gt;
for full details about such compartments and how to restrict the
operations that can be performed in them.

If you use the C&lt;PACKAGE&gt; option with C&lt;SAFE&gt;, the package you specify
will be placed into the safe compartment and evaluation will take
place in that package as usual.  

If not, C&lt;SAFE&gt; operation is a little different from the default.
Usually, if you don't specify a package, evaluation of program
fragments occurs in the package from which the template was invoked.
But in C&lt;SAFE&gt; mode the evaluation occurs inside the safe compartment
and cannot affect the calling package.  Normally, if you use C&lt;HASH&gt;
without C&lt;PACKAGE&gt;, the hash variables are imported into a private,
one-use-only package.  But if you use C&lt;HASH&gt; and C&lt;SAFE&gt; together
without C&lt;PACKAGE&gt;, the hash variables will just be loaded into the
root namespace of the C&lt;Safe&gt; compartment.

=item C&lt;OUTPUT&gt;

If your template is going to generate a lot of text that you are just
going to print out again anyway,  you can save memory by having
C&lt;Text::Template&gt; print out the text as it is generated instead of
making it into a big string and returning the string.  If you supply
the C&lt;OUTPUT&gt; option to C&lt;fill_in&gt;, the value should be a filehandle.
The generated text will be printed to this filehandle as it is
constructed.  For example:

	$template-&gt;fill_in(OUTPUT =&gt; \*STDOUT, ...);

fills in the C&lt;$template&gt; as usual, but the results are immediately
printed to STDOUT.  This may result in the output appearing more
quickly than it would have otherwise.

If you use C&lt;OUTPUT&gt;, the return value from C&lt;fill_in&gt; is still true on
success and false on failure, but the complete text is not returned to
the caller.

=item C&lt;PREPEND&gt;

You can have some Perl code prepended automatically to the beginning
of every program fragment.  See L&lt;C&lt;PREPEND&gt; feature and using
C&lt;strict&gt; in templates&gt; below.

=item C&lt;DELIMITERS&gt;

If this option is present, its value should be a reference to a list
of two strings.  The first string is the string that signals the
beginning of each program fragment, and the second string is the
string that signals the end of each program fragment.  See
L&lt;"Alternative Delimiters"&gt;, below.  

If you specify C&lt;DELIMITERS&gt; in the call to C&lt;fill_in&gt;, they override
any delimiters you set when you created the template object with
C&lt;new&gt;. 

=back

=head1 Convenience Functions

=head2 C&lt;fill_this_in&gt;

The basic way to fill in a template is to create a template object and
then call C&lt;fill_in&gt; on it.   This is useful if you want to fill in
the same template more than once.

In some programs, this can be cumbersome.  C&lt;fill_this_in&gt; accepts a
string, which contains the template, and a list of options, which are
passed to C&lt;fill_in&gt; as above.  It constructs the template object for
you, fills it in as specified, and returns the results.  It returns
C&lt;undef&gt; and sets C&lt;$Text::Template::ERROR&gt; if it couldn't generate
any results.

An example:

	$Q::name = 'Donald';
	$Q::amount = 141.61;
	$Q::part = 'hyoid bone';

	$text = Text::Template-&gt;fill_this_in( &lt;&lt;'EOM', PACKAGE =&gt; Q);
	Dear {$name},
	You owe me \\${sprintf('%.2f', $amount)}.  
	Pay or I will break your {$part}.
		Love,
		Grand Vizopteryx of Irkutsk.
	EOM

Notice how we included the template in-line in the program by using a
`here document' with the C&lt;E&lt;lt&gt;E&lt;lt&gt;&gt; notation.

C&lt;fill_this_in&gt; is a deprecated feature.  It is only here for
backwards compatibility, and may be removed in some far-future version
in C&lt;Text::Template&gt;.  You should use C&lt;fill_in_string&gt; instead.  It
is described in the next section.

=head2 C&lt;fill_in_string&gt;

It is stupid that C&lt;fill_this_in&gt; is a class method.  It should have
been just an imported function, so that you could omit the
C&lt;Text::Template-E&lt;gt&gt;&gt; in the example above.  But I made the mistake
four years ago and it is too late to change it.

C&lt;fill_in_string&gt; is exactly like C&lt;fill_this_in&gt; except that it is
not a method and you can omit the C&lt;Text::Template-E&lt;gt&gt;&gt; and just say

	print fill_in_string(&lt;&lt;'EOM', ...);
	Dear {$name},
	  ...
	EOM

To use C&lt;fill_in_string&gt;, you need to say

	use Text::Template 'fill_in_string';

at the top of your program.   You should probably use
C&lt;fill_in_string&gt; instead of C&lt;fill_this_in&gt;.

=head2 C&lt;fill_in_file&gt;

If you import C&lt;fill_in_file&gt;, you can say

	$text = fill_in_file(filename, ...);

The C&lt;...&gt; are passed to C&lt;fill_in&gt; as above.  The filename is the
name of the file that contains the template you want to fill in.  It
returns the result text. or C&lt;undef&gt;, as usual.

If you are going to fill in the same file more than once in the same
program you should use the longer C&lt;new&gt; / C&lt;fill_in&gt; sequence instead.
It will be a lot faster because it only has to read and parse the file
once.

=head2 Including files into templates

People always ask for this.  ``Why don't you have an include
function?'' they want to know.  The short answer is this is Perl, and
Perl already has an include function.  If you want it, you can just put

	{qx{cat filename}}

into your template.  VoilE&lt;agrave&gt;.

If you don't want to use C&lt;cat&gt;, you can write a little four-line
function that opens a file and dumps out its contents, and call it
from the template.  I wrote one for you.  In the template, you can say

	{Text::Template::_load_text(filename)}

If that is too verbose, here is a trick.  Suppose the template package
that you are going to be mentioning in the C&lt;fill_in&gt; call is package
C&lt;Q&gt;.  Then in the main program, write

	*Q::include = \&amp;Text::Template::_load_text;

This imports the C&lt;_load_text&gt; function into package C&lt;Q&gt; with the
name C&lt;include&gt;.  From then on, any template that you fill in with
package C&lt;Q&gt; can say

	{include(filename)}

to insert the text from the named file at that point.  If you are
using the C&lt;HASH&gt; option instead, just put C&lt;include =E&lt;gt&gt;
\&amp;Text::Template::_load_text&gt; into the hash instead of importing it
explicitly.

Suppose you don't want to insert a plain text file, but rather you
want to include one template within another?  Just use C&lt;fill_in_file&gt;
in the template itself:

	{Text::Template::fill_in_file(filename)}

You can do the same importing trick if this is too much to type.

=head1 Miscellaneous

=head2 C&lt;my&gt; variables

People are frequently surprised when this doesn't work:

	my $recipient = 'The King';
	my $text = fill_in_file('formletter.tmpl');

The text C&lt;The King&gt; doesn't get into the form letter.  Why not?
Because C&lt;$recipient&gt; is a C&lt;my&gt; variable, and the whole point of
C&lt;my&gt; variables is that they're private and inaccessible except in the
scope in which they're declared.  The template is not part of that
scope, so the template can't see C&lt;$recipient&gt;.  

If that's not the behavior you want, don't use C&lt;my&gt;.  C&lt;my&gt; means a
private variable, and in this case you don't want the variable to be
private.  Put the variables into package variables in some other
package, and use the C&lt;PACKAGE&gt; option to C&lt;fill_in&gt;:

	$Q::recipient = $recipient;
	my $text = fill_in_file('formletter.tmpl', PACKAGE =&gt; 'Q');
	

or pass the names and values in a hash with the C&lt;HASH&gt; option:

	my $text = fill_in_file('formletter.tmpl', HASH =&gt; { recipient =&gt; $recipient });

=head2 Security Matters

All variables are evaluated in the package you specify with the
C&lt;PACKAGE&gt; option of C&lt;fill_in&gt;.  if you use this option, and if your
templates don't do anything egregiously stupid, you won't have to
worry that evaluation of the little programs will creep out into the
rest of your program and wreck something.

Nevertheless, there's really no way (except with C&lt;Safe&gt;) to protect
against a template that says

	{ $Important::Secret::Security::Enable = 0; 
	  # Disable security checks in this program 
	}

or

	{ $/ = "ho ho ho";   # Sabotage future uses of &lt;FH&gt;.
	  # $/ is always a global variable
	}

or even

	{ system("rm -rf /") }

so B&lt;don't&gt; go filling in templates unless you're sure you know what's
in them.  If you're worried, or you can't trust the person who wrote
the template, use the C&lt;SAFE&gt; option.

A final warning: program fragments run a small risk of accidentally
clobbering local variables in the C&lt;fill_in&gt; function itself.  These
variables all have names that begin with C&lt;$fi_&gt;, so if you stay away
from those names you'll be safe.  (Of course, if you're a real wizard
you can tamper with them deliberately for exciting effects; this is
actually how C&lt;$OUT&gt; works.)  I can fix this, but it will make the
package slower to do it, so I would prefer not to.  If you are worried
about this, send me mail and I will show you what to do about it.

=head2 Alternative Delimiters

Lorenzo Valdettaro pointed out that if you are using C&lt;Text::Template&gt;
to generate TeX output, the choice of braces as the program fragment
delimiters makes you suffer suffer suffer.  Starting in version 1.20,
you can change the choice of delimiters to something other than curly
braces.

In either the C&lt;new()&gt; call or the C&lt;fill_in()&gt; call, you can specify
an alternative set of delimiters with the C&lt;DELIMITERS&gt; option.  For
example, if you would like code fragments to be delimited by C&lt;[@--&gt;
and C&lt;--@]&gt; instead of C&lt;{&gt; and C&lt;}&gt;, use

	... DELIMITERS =&gt; [ '[@--', '--@]' ], ...

Note that these delimiters are I&lt;literal strings&gt;, not regexes.  (I
tried for regexes, but it complicates the lexical analysis too much.)
Note also that C&lt;DELIMITERS&gt; disables the special meaning of the
backslash, so if you want to include the delimiters in the literal
text of your template file, you are out of luck---it is up to you to
choose delimiters that do not conflict with what you are doing.  The
delimiter strings may still appear inside of program fragments as long
as they nest properly.  This means that if for some reason you
absolutely must have a program fragment that mentions one of the
delimiters, like this:

	[@--
		print "Oh no, a delimiter: --@]\n"
	--@]

you may be able to make it work by doing this instead:

	[@--
		# Fake matching delimiter in a comment: [@--
		print "Oh no, a delimiter: --@]\n"
	--@]

It may be safer to choose delimiters that begin with a newline
character.  

Because the parsing of templates is simplified by the absence of
backslash escapes, using alternative C&lt;DELIMITERS&gt; may speed up the
parsing process by 20-25%.  This shows that my original choice of C&lt;{&gt;
and C&lt;}&gt; was very bad. 

=head2 C&lt;PREPEND&gt; feature and using C&lt;strict&gt; in templates

Suppose you would like to use C&lt;strict&gt; in your templates to detect
undeclared variables and the like.  But each code fragment is a
separate lexical scope, so you have to turn on C&lt;strict&gt; at the top of
each and every code fragment:

	{ use strict;
	  use vars '$foo';
	  $foo = 14;
	  ...
	}

	...

	{ # we forgot to put `use strict' here
	  my $result = $boo + 12;    # $boo is misspelled and should be $foo
	  # No error is raised on `$boo'
	}

Because we didn't put C&lt;use strict&gt; at the top of the second fragment,
it was only active in the first fragment, and we didn't get any
C&lt;strict&gt; checking in the second fragment.  Then we misspelled C&lt;$foo&gt;
and the error wasn't caught.  

C&lt;Text::Template&gt; version 1.22 and higher has a new feature to make
this easier.  You can specify that any text at all be automatically
added to the beginning of each program fragment.  

When you make a call to C&lt;fill_in&gt;, you can specify a

	PREPEND =&gt; 'some perl statements here'

option; the statements will be prepended to each program fragment for
that one call only.  Suppose that the C&lt;fill_in&gt; call included a

	PREPEND =&gt; 'use strict;'

option, and that the template looked like this:

	{ use vars '$foo';
	  $foo = 14;
	  ...
	}

	...

	{ my $result = $boo + 12;    # $boo is misspelled and should be $foo
	  ...
	}

The code in the second fragment would fail, because C&lt;$boo&gt; has not
been declared.  C&lt;use strict&gt; was implied, even though you did not
write it explicitly, because the C&lt;PREPEND&gt; option added it for you
automatically.

There are two other ways to do this.  At the time you create the
template object with C&lt;new&gt;, you can also supply a C&lt;PREPEND&gt; option,
in which case the statements will be prepended each time you fill in
that template.  If the C&lt;fill_in&gt; call has its own C&lt;PREPEND&gt; option,
this overrides the one specified at the time you created the
template.  Finally, you can make the class method call

	Text::Template-&gt;always_prepend('perl statements');

If you do this, then call calls to C&lt;fill_in&gt; for I&lt;any&gt; template will
attach the perl statements to the beginning of each program fragment,
except where overridden by C&lt;PREPEND&gt; options to C&lt;new&gt; or C&lt;fill_in&gt;.

=head2 Prepending in Derived Classes

This section is technical, and you should skip it on the first few
readings. 

Normally there are three places that prepended text could come from.
It could come from the C&lt;PREPEND&gt; option in the C&lt;fill_in&gt; call, from
the C&lt;PREPEND&gt; option in the C&lt;new&gt; call that created the template
object, or from the argument of the C&lt;always_prepend&gt; call.
C&lt;Text::Template&gt; looks for these three things in order and takes the
first one that it finds.

In a subclass of C&lt;Text::Template&gt;, this last possibility is
ambiguous.  Suppose C&lt;S&gt; is a subclass of C&lt;Text::Template&gt;.  Should 

	Text::Template-&gt;always_prepend(...);

affect objects in class C&lt;Derived&gt;?  The answer is that you can have it
either way.  

The C&lt;always_prepend&gt; value for C&lt;Text::Template&gt; is normally stored
in  a hash variable named C&lt;%GLOBAL_PREPEND&gt; under the key
C&lt;Text::Template&gt;.  When C&lt;Text::Template&gt; looks to see what text to
prepend, it first looks in the template object itself, and if not, it
looks in C&lt;$GLOBAL_PREPEND{I&lt;class&gt;}&gt; where I&lt;class&gt; is the class to
which the template object belongs.  If it doesn't find any value, it
looks in C&lt;$GLOBAL_PREPEND{'Text::Template'}&gt;.  This means that
objects in class C&lt;Derived&gt; I&lt;will&gt; be affected by

	Text::Template-&gt;always_prepend(...);

I&lt;unless&gt; there is also a call to

	Derived-&gt;always_prepend(...);

So when you're designing your derived class, you can arrange to have
your objects ignore C&lt;Text::Template::always_prepend&gt; calls by simply
putting C&lt;Derived-E&lt;gt&gt;always_prepend('')&gt; at the top of your module.

Of course, there is also a final escape hatch: Templates support a
C&lt;prepend_text&gt; that is used to look up the appropriate text to be
prepended at C&lt;fill_in&gt; time.  Your derived class can override this
method to get an arbitrary effect.

=head2 JavaScript

Jennifer D. St Clair asks:

	&gt; Most of my pages contain JavaScript and Stylesheets.
        &gt; How do I change the template identifier?  

Jennifer is worried about the braces in the JavaScript being taken as
the delimiters of the Perl program fragments.  Of course, disaster
will ensue when perl tries to evaluate these as if they were Perl
programs.  The best choice is to find some unambiguous delimiter
strings that you can use in your template instead of curly braces, and
then use the C&lt;DELIMITERS&gt; option.  However, if you can't do this for
some reason, there are  two easy workarounds:

1. You can put C&lt;\&gt; in front of C&lt;{&gt;, C&lt;}&gt;, or C&lt;\&gt; to remove its
special meaning.  So, for example, instead of

	    if (br== "n3") { 
		// etc.
	    }

you can put

	    if (br== "n3") \{ 
		// etc.
	    \}

and it'll come out of the template engine the way you want.

But here is another method that is probably better.  To see how it
works, first consider what happens if you put this into a template:

	    { 'foo' }

Since it's in braces, it gets evaluated, and obviously, this is going
to turn into

	    foo

So now here's the trick: In Perl, C&lt;q{...}&gt; is the same as C&lt;'...'&gt;.
So if we wrote

	    {q{foo}}

it would turn into 

	    foo

So for your JavaScript, just write

	    {q{if (br== "n3") { 
	  	 // etc.
	       }}
	    }

and it'll come out as

	      if (br== "n3") { 
	  	  // etc.
	      }

which is what you want.


=head2 Shut Up!

People sometimes try to put an initialization section at the top of
their templates, like this:

	{ ...
	  $var = 17;
	}

Then they complain because there is a C&lt;17&gt; at the top of the output
that they didn't want to have there.  

Remember that a program fragment is replaced with its own return
value, and that in Perl the return value of a code block is the value
of the last expression that was evaluated, which in this case is 17.
If it didn't do that, you wouldn't be able to write C&lt;{$recipient}&gt;
and have the recipient filled in.

To prevent the 17 from appearing in the output is very simple:

	{ ...
	  $var = 17;
	  '';
	}

Now the last expression evaluated yields the empty string, which is
invisible.  If you don't like the way this looks, use

	{ ...
	  $var = 17;
	  ($SILENTLY);
	}

instead.  Presumably, C&lt;$SILENTLY&gt; has no value, so nothing will be
interpolated.  This is what is known as a `trick'.

=head2 Compatibility

Every effort has been made to make this module compatible with older
versions.  The only known exceptions follow:

The output format of the default C&lt;BROKEN&gt; subroutine has changed
twice, most recently between versions 1.31 and 1.40.

Starting in version 1.10, the C&lt;$OUT&gt; variable is arrogated for a
special meaning.  If you had templates before version 1.10 that
happened to use a variable named C&lt;$OUT&gt;, you will have to change them
to use some other variable or all sorts of strangeness will result.

Between versions 0.1b and 1.00 the behavior of the \ metacharacter
changed.  In 0.1b, \\ was special everywhere, and the template
processor always replaced it with a single backslash before passing
the code to Perl for evaluation.  The rule now is more complicated but
probably more convenient.  See the section on backslash processing,
below, for a full discussion.

=head2 Backslash Processing

In C&lt;Text::Template&gt; beta versions, the backslash was special whenever
it appeared before a brace or another backslash.  That meant that
while C&lt;{"\n"}&gt; did indeed generate a newline, C&lt;{"\\"}&gt; did not
generate a backslash, because the code passed to Perl for evaluation
was C&lt;"\"&gt; which is a syntax error.  If you wanted a backslash, you
would have had to write C&lt;{"\\\\"}&gt;.

In C&lt;Text::Template&gt; versions 1.00 through 1.10, there was a bug:
Backslash was special everywhere.  In these versions, C&lt;{"\n"}&gt;
generated the letter C&lt;n&gt;.

The bug has been corrected in version 1.11, but I did not go back to
exactly the old rule, because I did not like the idea of having to
write C&lt;{"\\\\"}&gt; to get one backslash.  The rule is now more
complicated to remember, but probably easier to use.  The rule is now:
Backslashes are always passed to Perl unchanged I&lt;unless&gt; they occur
as part of a sequence like C&lt;\\\\\\{&gt; or C&lt;\\\\\\}&gt;.  In these
contexts, they are special; C&lt;\\&gt; is replaced with C&lt;\&gt;, and C&lt;\{&gt; and
C&lt;\}&gt; signal a literal brace. 

Examples:

	\{ foo \}

is I&lt;not&gt; evaluated, because the C&lt;\&gt; before the braces signals that
they should be taken literally.  The result in the output looks like this: 

	{ foo }


This is a syntax error:

	{ "foo}" }

because C&lt;Text::Template&gt; thinks that the code ends at the first C&lt;}&gt;,
and then gets upset when it sees the second one.  To make this work
correctly, use

	{ "foo\}" }

This passes C&lt;"foo}"&gt; to Perl for evaluation.  Note there's no C&lt;\&gt; in
the evaluated code.  If you really want a C&lt;\&gt; in the evaluated code,
use

	{ "foo\\\}" }

This passes C&lt;"foo\}"&gt; to Perl for evaluation.

Starting with C&lt;Text::Template&gt; version 1.20, backslash processing is
disabled if you use the C&lt;DELIMITERS&gt; option to specify alternative
delimiter strings.

=head2 A short note about C&lt;$Text::Template::ERROR&gt;

In the past some people have fretted about `violating the package
boundary' by examining a variable inside the C&lt;Text::Template&gt;
package.  Don't feel this way.  C&lt;$Text::Template::ERROR&gt; is part of
the published, official interface to this package.  It is perfectly OK
to inspect this variable.  The interface is not going to change.

If it really, really bothers you, you can import a function called
C&lt;TTerror&gt; that returns the current value of the C&lt;$ERROR&gt; variable.
So you can say:

	use Text::Template 'TTerror';

	my $template = new Text::Template (SOURCE =&gt; $filename);
	unless ($template) {
	  my $err = TTerror;
	  die "Couldn't make template: $err; aborting";
	}

I don't see what benefit this has over just doing this:

	use Text::Template;

	my $template = new Text::Template (SOURCE =&gt; $filename)
	  or die "Couldn't make template: $Text::Template::ERROR; aborting";

But if it makes you happy to do it that way, go ahead.

=head2 Sticky Widgets in Template Files

The C&lt;CGI&gt; module provides functions for `sticky widgets', which are
form input controls that retain their values from one page to the
next.   Sometimes people want to know how to include these widgets
into their template output.

It's totally straightforward.  Just call the C&lt;CGI&gt; functions from
inside the template:

	{ $q-&gt;checkbox_group(NAME =&gt; 'toppings',
		  	     LINEBREAK =&gt; true,
			     COLUMNS =&gt; 3,
			     VALUES =&gt; \@toppings,
			    );
	}

=head2 Automatic preprocessing of program fragments

It may be useful to preprocess the program fragments before they are
evaluated.  See C&lt;Text::Template::Preprocess&gt; for more details.

=head2 Automatic postprocessing of template hunks

It may be useful to process hunks of output before they are appended to
the result text.  For this, subclass and replace the C&lt;append_text_to_result&gt;
method.  It is passed a list of pairs with these entries:

  handle - a filehandle to which to print the desired output
  out    - a ref to a string to which to append, to use if handle is not given
  text   - the text that will be appended
  type   - where the text came from: TEXT for literal text, PROG for code

=head2 Author

Mark Jason Dominus, Plover Systems

Please send questions and other remarks about this software to
C&lt;mjd-perl-template+@plover.com&gt;

You can join a very low-volume (E&lt;lt&gt;10 messages per year) mailing
list for announcements about this package.  Send an empty note to
C&lt;mjd-perl-template-request@plover.com&gt; to join.

For updates, visit C&lt;http://www.plover.com/~mjd/perl/Template/&gt;.

=head2 Support?

This software is version 1.46.  It may have bugs.  Suggestions and bug
reports are always welcome.  Send them to
C&lt;mjd-perl-template+@plover.com&gt;.  (That is my address, not the address
of the mailing list.  The mailing list address is a secret.)

=head1 LICENSE

    Text::Template version 1.46
    Copyright 2013 Mark Jason Dominus

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  You may also can
    redistribute it and/or modify it under the terms of the Perl
    Artistic License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received copies of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


=head1 THANKS

Many thanks to the following people for offering support,
encouragement, advice, bug reports, and all the other good stuff.  

David H. Adler /
Joel Appelbaum /
Klaus Arnhold /
AntE&lt;oacute&gt;nio AragE&lt;atilde&gt;o /
Kevin Atteson /
Chris.Brezil /
Mike Brodhead /
Tom Brown /
Dr. Frank Bucolo /
Tim Bunce /
Juan E. Camacho /
Itamar Almeida de Carvalho /
Joseph Cheek /
Gene Damon /
San Deng /
Bob Dougherty /
Marek Grac /
Dan Franklin /
gary at dls.net /
Todd A. Green /
Donald L. Greer Jr. /
Michelangelo Grigni /
Zac Hansen /
Tom Henry /
Jarko Hietaniemi /
Matt X. Hunter /
Robert M. Ioffe /
Daniel LaLiberte /
Reuven M. Lerner /
Trip Lilley / 
Yannis Livassof /
Val Luck /
Kevin Madsen /
David Marshall /
James Mastros /
Joel Meulenberg /
Jason Moore /
Sergey Myasnikov /
Chris Nandor /
Bek Oberin /
Steve Palincsar /
Ron Pero /
Hans Persson /
Sean Roehnelt /
Jonathan Roy /
Shabbir J. Safdar /
Jennifer D. St Clair /
Uwe Schneider /
Randal L. Schwartz /
Michael G Schwern /
Yonat Sharon /
Brian C. Shensky /
Niklas Skoglund /
Tom Snee /
Fred Steinberg /
Hans Stoop /
Michael J. Suzio /
Dennis Taylor /
James H. Thompson /
Shad Todd /
Lieven Tomme /
Lorenzo Valdettaro /
Larry Virden /
Andy Wardley /
Archie Warnock /
Chris Wesley /
Matt Womer /
Andrew G Wood /
Daini Xie /
Michaely Yeung

Special thanks to:

=over 2

=item Jonathan Roy 

for telling me how to do the C&lt;Safe&gt; support (I spent two years
worrying about it, and then Jonathan pointed out that it was trivial.)

=item Ranjit Bhatnagar 

for demanding less verbose fragments like they have in ASP, for
helping me figure out the Right Thing, and, especially, for talking me
out of adding any new syntax.  These discussions resulted in the
C&lt;$OUT&gt; feature.

=back

=head2 Bugs and Caveats

C&lt;my&gt; variables in C&lt;fill_in&gt; are still susceptible to being clobbered
by template evaluation.  They all begin with C&lt;fi_&gt;, so avoid those
names in your templates.

The line number information will be wrong if the template's lines are
not terminated by C&lt;"\n"&gt;.  You should let me know if this is a
problem.  If you do, I will fix it.

The C&lt;$OUT&gt; variable has a special meaning in templates, so you cannot
use it as if it were a regular variable.

There are not quite enough tests in the test suite.

=cut
</pre></body></html>