dc4f3bac77e115cf2fb72cccf65977edb04c6e59
[openssl.git] / external / perl / Text-Template-1.46 / lib / Text / Template.pm
1 # -*- perl -*-
2 # Text::Template.pm
3 #
4 # Fill in `templates'
5 #
6 # Copyright 2013 M. J. Dominus.
7 # You may copy and distribute this program under the
8 # same terms as Perl iteself.  
9 # If in doubt, write to mjd-perl-template+@plover.com for a license.
10 #
11 # Version 1.46
12
13 package Text::Template;
14 require 5.004;
15 use Exporter;
16 @ISA = qw(Exporter);
17 @EXPORT_OK = qw(fill_in_file fill_in_string TTerror);
18 use vars '$ERROR';
19 use strict;
20
21 $Text::Template::VERSION = '1.46';
22 my %GLOBAL_PREPEND = ('Text::Template' => '');
23
24 sub Version {
25   $Text::Template::VERSION;
26 }
27
28 sub _param {
29   my $kk;
30   my ($k, %h) = @_;
31   for $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") {
32     return $h{$kk} if exists $h{$kk};
33   }
34   return;
35 }
36
37 sub always_prepend
38 {
39   my $pack = shift;
40   my $old = $GLOBAL_PREPEND{$pack};
41   $GLOBAL_PREPEND{$pack} = shift;
42   $old;
43 }
44
45 {
46   my %LEGAL_TYPE;
47   BEGIN { 
48     %LEGAL_TYPE = map {$_=>1} qw(FILE FILEHANDLE STRING ARRAY);
49   }
50   sub new {
51     my $pack = shift;
52     my %a = @_;
53     my $stype = uc(_param('type', %a) || "FILE");
54     my $source = _param('source', %a);
55     my $untaint = _param('untaint', %a);
56     my $prepend = _param('prepend', %a);
57     my $alt_delim = _param('delimiters', %a);
58     my $broken = _param('broken', %a);
59     unless (defined $source) {
60       require Carp;
61       Carp::croak("Usage: $ {pack}::new(TYPE => ..., SOURCE => ...)");
62     }
63     unless ($LEGAL_TYPE{$stype}) {
64       require Carp;
65       Carp::croak("Illegal value `$stype' for TYPE parameter");
66     }
67     my $self = {TYPE => $stype,
68                 PREPEND => $prepend,
69                 UNTAINT => $untaint,
70                 BROKEN => $broken,
71                 (defined $alt_delim ? (DELIM => $alt_delim) : ()),
72                };
73     # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken
74     # are tainted, all the others become tainted too as a result of
75     # sharing the expression with them.  We install $source separately
76     # to prevent it from acquiring a spurious taint.
77     $self->{SOURCE} = $source;
78
79     bless $self => $pack;
80     return unless $self->_acquire_data;
81     
82     $self;
83   }
84 }
85
86 # Convert template objects of various types to type STRING,
87 # in which the template data is embedded in the object itself.
88 sub _acquire_data {
89   my ($self) = @_;
90   my $type = $self->{TYPE};
91   if ($type eq 'STRING') {
92     # nothing necessary    
93   } elsif ($type eq 'FILE') {
94     my $data = _load_text($self->{SOURCE});
95     unless (defined $data) {
96       # _load_text already set $ERROR
97       return undef;
98     }
99     if ($self->{UNTAINT} && _is_clean($self->{SOURCE})) {
100       _unconditionally_untaint($data);
101     }
102     $self->{TYPE} = 'STRING';
103     $self->{FILENAME} = $self->{SOURCE};
104     $self->{SOURCE} = $data;
105   } elsif ($type eq 'ARRAY') {
106     $self->{TYPE} = 'STRING';
107     $self->{SOURCE} = join '', @{$self->{SOURCE}};
108   } elsif ($type eq 'FILEHANDLE') {
109     $self->{TYPE} = 'STRING';
110     local $/;
111     my $fh = $self->{SOURCE};
112     my $data = <$fh>; # Extra assignment avoids bug in Solaris perl5.00[45].
113     if ($self->{UNTAINT}) {
114       _unconditionally_untaint($data);
115     }
116     $self->{SOURCE} = $data;
117   } else {
118     # This should have been caught long ago, so it represents a 
119     # drastic `can't-happen' sort of failure
120     my $pack = ref $self;
121     die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting";
122   }
123   $self->{DATA_ACQUIRED} = 1;
124 }
125
126 sub source {
127   my ($self) = @_;
128   $self->_acquire_data unless $self->{DATA_ACQUIRED};
129   return $self->{SOURCE};
130 }
131
132 sub set_source_data {
133   my ($self, $newdata) = @_;
134   $self->{SOURCE} = $newdata;
135   $self->{DATA_ACQUIRED} = 1;
136   $self->{TYPE} = 'STRING';
137   1;
138 }
139
140 sub compile {
141   my $self = shift;
142
143   return 1 if $self->{TYPE} eq 'PREPARSED';
144
145   return undef unless $self->_acquire_data;
146   unless ($self->{TYPE} eq 'STRING') {
147     my $pack = ref $self;
148     # This should have been caught long ago, so it represents a 
149     # drastic `can't-happen' sort of failure
150     die "Can only compile $pack objects of subtype STRING, but this is $self->{TYPE}; aborting";
151   }
152
153   my @tokens;
154   my $delim_pats = shift() || $self->{DELIM};
155
156   
157
158   my ($t_open, $t_close) = ('{', '}');
159   my $DELIM;                    # Regex matches a delimiter if $delim_pats
160   if (defined $delim_pats) {
161     ($t_open, $t_close) = @$delim_pats;
162     $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))";
163     @tokens = split /($DELIM|\n)/, $self->{SOURCE};
164   } else {
165     @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self->{SOURCE};
166   }
167   my $state = 'TEXT';
168   my $depth = 0;
169   my $lineno = 1;
170   my @content;
171   my $cur_item = '';
172   my $prog_start;
173   while (@tokens) {
174     my $t = shift @tokens;
175     next if $t eq '';
176     if ($t eq $t_open) {        # Brace or other opening delimiter
177       if ($depth == 0) {
178         push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
179         $cur_item = '';
180         $state = 'PROG';
181         $prog_start = $lineno;
182       } else {
183         $cur_item .= $t;
184       }
185       $depth++;
186     } elsif ($t eq $t_close) {  # Brace or other closing delimiter
187       $depth--;
188       if ($depth < 0) {
189         $ERROR = "Unmatched close brace at line $lineno";
190         return undef;
191       } elsif ($depth == 0) {
192         push @content, [$state, $cur_item, $prog_start] if $cur_item ne '';
193         $state = 'TEXT';
194         $cur_item = '';
195       } else {
196         $cur_item .= $t;
197       }
198     } elsif (!$delim_pats && $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\}
199       $cur_item .= '\\';
200     } elsif (!$delim_pats && $t =~ /^\\([{}])$/) { # Escaped (literal) brace?
201         $cur_item .= $1;
202     } elsif ($t eq "\n") {      # Newline
203       $lineno++;
204       $cur_item .= $t;
205     } else {                    # Anything else
206       $cur_item .= $t;
207     }
208   }
209
210   if ($state eq 'PROG') {
211     $ERROR = "End of data inside program text that began at line $prog_start";
212     return undef;
213   } elsif ($state eq 'TEXT') {
214     push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
215   } else {
216     die "Can't happen error #1";
217   }
218   
219   $self->{TYPE} = 'PREPARSED';
220   $self->{SOURCE} = \@content;
221   1;
222 }
223
224 sub prepend_text {
225   my ($self) = @_;
226   my $t = $self->{PREPEND};
227   unless (defined $t) {
228     $t = $GLOBAL_PREPEND{ref $self};
229     unless (defined $t) {
230       $t = $GLOBAL_PREPEND{'Text::Template'};
231     }
232   }
233   $self->{PREPEND} = $_[1] if $#_ >= 1;
234   return $t;
235 }
236
237 sub fill_in {
238   my $fi_self = shift;
239   my %fi_a = @_;
240
241   unless ($fi_self->{TYPE} eq 'PREPARSED') {
242     my $delims = _param('delimiters', %fi_a);
243     my @delim_arg = (defined $delims ? ($delims) : ());
244     $fi_self->compile(@delim_arg)
245       or return undef;
246   }
247
248   my $fi_varhash = _param('hash', %fi_a);
249   my $fi_package = _param('package', %fi_a) ;
250   my $fi_broken  = 
251     _param('broken', %fi_a)  || $fi_self->{BROKEN} || \&_default_broken;
252   my $fi_broken_arg = _param('broken_arg', %fi_a) || [];
253   my $fi_safe = _param('safe', %fi_a);
254   my $fi_ofh = _param('output', %fi_a);
255   my $fi_eval_package;
256   my $fi_scrub_package = 0;
257   my $fi_filename = _param('filename') || $fi_self->{FILENAME} || 'template';
258
259   my $fi_prepend = _param('prepend', %fi_a);
260   unless (defined $fi_prepend) {
261     $fi_prepend = $fi_self->prepend_text;
262   }
263
264   if (defined $fi_safe) {
265     $fi_eval_package = 'main';
266   } elsif (defined $fi_package) {
267     $fi_eval_package = $fi_package;
268   } elsif (defined $fi_varhash) {
269     $fi_eval_package = _gensym();
270     $fi_scrub_package = 1;
271   } else {
272     $fi_eval_package = caller;
273   }
274
275   my $fi_install_package;
276   if (defined $fi_varhash) {
277     if (defined $fi_package) {
278       $fi_install_package = $fi_package;
279     } elsif (defined $fi_safe) {
280       $fi_install_package = $fi_safe->root;
281     } else {
282       $fi_install_package = $fi_eval_package; # The gensymmed one
283     }
284     _install_hash($fi_varhash => $fi_install_package);
285   }
286
287   if (defined $fi_package && defined $fi_safe) {
288     no strict 'refs';
289     # Big fat magic here: Fix it so that the user-specified package
290     # is the default one available in the safe compartment.
291     *{$fi_safe->root . '::'} = \%{$fi_package . '::'};   # LOD
292   }
293
294   my $fi_r = '';
295   my $fi_item;
296   foreach $fi_item (@{$fi_self->{SOURCE}}) {
297     my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
298     if ($fi_type eq 'TEXT') {
299       $fi_self->append_text_to_output(
300         text   => $fi_text,
301         handle => $fi_ofh,
302         out    => \$fi_r,
303         type   => $fi_type,
304       );
305     } elsif ($fi_type eq 'PROG') {
306       no strict;
307       my $fi_lcomment = "#line $fi_lineno $fi_filename";
308       my $fi_progtext = 
309         "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;";
310       my $fi_res;
311       my $fi_eval_err = '';
312       if ($fi_safe) {
313         $fi_safe->reval(q{undef $OUT});
314         $fi_res = $fi_safe->reval($fi_progtext);
315         $fi_eval_err = $@;
316         my $OUT = $fi_safe->reval('$OUT');
317         $fi_res = $OUT if defined $OUT;
318       } else {
319         my $OUT;
320         $fi_res = eval $fi_progtext;
321         $fi_eval_err = $@;
322         $fi_res = $OUT if defined $OUT;
323       }
324
325       # If the value of the filled-in text really was undef,
326       # change it to an explicit empty string to avoid undefined
327       # value warnings later.
328       $fi_res = '' unless defined $fi_res;
329
330       if ($fi_eval_err) {
331         $fi_res = $fi_broken->(text => $fi_text,
332                                error => $fi_eval_err,
333                                lineno => $fi_lineno,
334                                arg => $fi_broken_arg,
335                                );
336         if (defined $fi_res) {
337           $fi_self->append_text_to_output(
338             text   => $fi_res,
339             handle => $fi_ofh,
340             out    => \$fi_r,
341             type   => $fi_type,
342           );
343         } else {
344           return $fi_res;               # Undefined means abort processing
345         }
346       } else {
347         $fi_self->append_text_to_output(
348           text   => $fi_res,
349           handle => $fi_ofh,
350           out    => \$fi_r,
351           type   => $fi_type,
352         );
353       }
354     } else {
355       die "Can't happen error #2";
356     }
357   }
358
359   _scrubpkg($fi_eval_package) if $fi_scrub_package;
360   defined $fi_ofh ? 1 : $fi_r;
361 }
362
363 sub append_text_to_output {
364   my ($self, %arg) = @_;
365
366   if (defined $arg{handle}) {
367     print { $arg{handle} } $arg{text};
368   } else {
369     ${ $arg{out} } .= $arg{text};
370   }
371
372   return;
373 }
374
375 sub fill_this_in {
376   my $pack = shift;
377   my $text = shift;
378   my $templ = $pack->new(TYPE => 'STRING', SOURCE => $text, @_)
379     or return undef;
380   $templ->compile or return undef;
381   my $result = $templ->fill_in(@_);
382   $result;
383 }
384
385 sub fill_in_string {
386   my $string = shift;
387   my $package = _param('package', @_);
388   push @_, 'package' => scalar(caller) unless defined $package;
389   Text::Template->fill_this_in($string, @_);
390 }
391
392 sub fill_in_file {
393   my $fn = shift;
394   my $templ = Text::Template->new(TYPE => 'FILE', SOURCE => $fn, @_)
395     or return undef;
396   $templ->compile or return undef;
397   my $text = $templ->fill_in(@_);
398   $text;
399 }
400
401 sub _default_broken {
402   my %a = @_;
403   my $prog_text = $a{text};
404   my $err = $a{error};
405   my $lineno = $a{lineno};
406   chomp $err;
407 #  $err =~ s/\s+at .*//s;
408   "Program fragment delivered error ``$err''";
409 }
410
411 sub _load_text {
412   my $fn = shift;
413   local *F;
414   unless (open F, $fn) {
415     $ERROR = "Couldn't open file $fn: $!";
416     return undef;
417   }
418   local $/;
419   <F>;
420 }
421
422 sub _is_clean {
423   my $z;
424   eval { ($z = join('', @_)), eval '#' . substr($z,0,0); 1 }   # LOD
425 }
426
427 sub _unconditionally_untaint {
428   for (@_) {
429     ($_) = /(.*)/s;
430   }
431 }
432
433 {
434   my $seqno = 0;
435   sub _gensym {
436     __PACKAGE__ . '::GEN' . $seqno++;
437   }
438   sub _scrubpkg {
439     my $s = shift;
440     $s =~ s/^Text::Template:://;
441     no strict 'refs';
442     my $hash = $Text::Template::{$s."::"};
443     foreach my $key (keys %$hash) {
444       undef $hash->{$key};
445     }
446   }
447 }
448   
449 # Given a hashful of variables (or a list of such hashes)
450 # install the variables into the specified package,
451 # overwriting whatever variables were there before.
452 sub _install_hash {
453   my $hashlist = shift;
454   my $dest = shift;
455   if (UNIVERSAL::isa($hashlist, 'HASH')) {
456     $hashlist = [$hashlist];
457   }
458   my $hash;
459   foreach $hash (@$hashlist) {
460     my $name;
461     foreach $name (keys %$hash) {
462       my $val = $hash->{$name};
463       no strict 'refs';
464       local *SYM = *{"$ {dest}::$name"};
465       if (! defined $val) {
466         delete ${"$ {dest}::"}{$name};
467       } elsif (ref $val) {
468         *SYM = $val;
469       } else {
470         *SYM = \$val;
471       }
472     }
473   }
474 }
475
476 sub TTerror { $ERROR }
477
478 1;
479
480
481 =head1 NAME 
482
483 Text::Template - Expand template text with embedded Perl
484
485 =head1 VERSION
486
487 This file documents C<Text::Template> version B<1.46>
488
489 =head1 SYNOPSIS
490
491  use Text::Template;
492
493
494  $template = Text::Template->new(TYPE => 'FILE',  SOURCE => 'filename.tmpl');
495  $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] );
496  $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh );
497  $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' );
498  $template = Text::Template->new(PREPEND => q{use strict;}, ...);
499
500  # Use a different template file syntax:
501  $template = Text::Template->new(DELIMITERS => [$open, $close], ...);
502
503  $recipient = 'King';
504  $text = $template->fill_in();  # Replaces `{$recipient}' with `King'
505  print $text;
506
507  $T::recipient = 'Josh';
508  $text = $template->fill_in(PACKAGE => T);
509
510  # Pass many variables explicitly
511  $hash = { recipient => 'Abed-Nego',
512            friends => [ 'me', 'you' ],
513            enemies => { loathsome => 'Bill Gates',
514                         fearsome => 'Larry Ellison' },
515          };
516  $text = $template->fill_in(HASH => $hash, ...);
517  # $recipient is Abed-Nego,
518  # @friends is ( 'me', 'you' ),
519  # %enemies is ( loathsome => ..., fearsome => ... )
520
521
522  # Call &callback in case of programming errors in template
523  $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...);
524
525  # Evaluate program fragments in Safe compartment with restricted permissions
526  $text = $template->fill_in(SAFE => $compartment, ...);
527
528  # Print result text instead of returning it
529  $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...);
530
531  # Parse template with different template file syntax:
532  $text = $template->fill_in(DELIMITERS => [$open, $close], ...);
533  # Note that this is *faster* than using the default delimiters
534
535  # Prepend specified perl code to each fragment before evaluating:
536  $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...);
537
538  use Text::Template 'fill_in_string';
539  $text = fill_in_string( <<EOM, PACKAGE => 'T', ...);
540  Dear {$recipient},
541  Pay me at once.
542         Love, 
543          G.V.
544  EOM
545
546  use Text::Template 'fill_in_file';
547  $text = fill_in_file($filename, ...);
548
549  # All templates will always have `use strict vars' attached to all fragments
550  Text::Template->always_prepend(q{use strict 'vars';});
551
552 =head1 DESCRIPTION
553
554 This is a library for generating form letters, building HTML pages, or
555 filling in templates generally.  A `template' is a piece of text that
556 has little Perl programs embedded in it here and there.  When you
557 `fill in' a template, you evaluate the little programs and replace
558 them with their values.  
559
560 You can store a template in a file outside your program.  People can
561 modify the template without modifying the program.  You can separate
562 the formatting details from the main code, and put the formatting
563 parts of the program into the template.  That prevents code bloat and
564 encourages functional separation.
565
566 =head2 Example
567
568 Here's an example of a template, which we'll suppose is stored in the
569 file C<formletter.tmpl>:
570
571         Dear {$title} {$lastname},
572
573         It has come to our attention that you are delinquent in your
574         {$monthname[$last_paid_month]} payment.  Please remit
575         ${sprintf("%.2f", $amount)} immediately, or your patellae may
576         be needlessly endangered.
577
578                         Love,
579
580                         Mark "Vizopteryx" Dominus
581
582
583 The result of filling in this template is a string, which might look
584 something like this:
585
586         Dear Mr. Gates,
587
588         It has come to our attention that you are delinquent in your
589         February payment.  Please remit
590         $392.12 immediately, or your patellae may
591         be needlessly endangered.
592
593
594                         Love,
595
596                         Mark "Vizopteryx" Dominus
597
598 Here is a complete program that transforms the example
599 template into the example result, and prints it out:
600
601         use Text::Template;
602
603         my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
604           or die "Couldn't construct template: $Text::Template::ERROR";
605
606         my @monthname = qw(January February March April May June
607                            July August September October November December);
608         my %vars = (title => 'Mr.',
609                     firstname => 'Bill',
610                     lastname => 'Gates',
611                     last_paid_month => 1,   # February
612                     amount => 392.12,
613                     monthname => \@monthname,
614                    );
615
616         my $result = $template->fill_in(HASH => \%vars);
617
618         if (defined $result) { print $result }
619         else { die "Couldn't fill in template: $Text::Template::ERROR" }
620
621
622 =head2 Philosophy
623
624 When people make a template module like this one, they almost always
625 start by inventing a special syntax for substitutions.  For example,
626 they build it so that a string like C<%%VAR%%> is replaced with the
627 value of C<$VAR>.  Then they realize the need extra formatting, so
628 they put in some special syntax for formatting.  Then they need a
629 loop, so they invent a loop syntax.  Pretty soon they have a new
630 little template language.
631
632 This approach has two problems: First, their little language is
633 crippled. If you need to do something the author hasn't thought of,
634 you lose.  Second: Who wants to learn another language?  You already
635 know Perl, so why not use it?
636
637 C<Text::Template> templates are programmed in I<Perl>.  You embed Perl
638 code in your template, with C<{> at the beginning and C<}> at the end.
639 If you want a variable interpolated, you write it the way you would in
640 Perl.  If you need to make a loop, you can use any of the Perl loop
641 constructions.  All the Perl built-in functions are available.
642
643 =head1 Details
644
645 =head2 Template Parsing
646
647 The C<Text::Template> module scans the template source.  An open brace
648 C<{> begins a program fragment, which continues until the matching
649 close brace C<}>.  When the template is filled in, the program
650 fragments are evaluated, and each one is replaced with the resulting
651 value to yield the text that is returned.
652
653 A backslash C<\> in front of a brace (or another backslash that is in
654 front of a brace) escapes its special meaning.  The result of filling
655 out this template:
656
657         \{ The sum of 1 and 2 is {1+2}  \}
658
659 is
660
661         { The sum of 1 and 2 is 3  }
662
663 If you have an unmatched brace, C<Text::Template> will return a
664 failure code and a warning about where the problem is.  Backslashes
665 that do not precede a brace are passed through unchanged.  If you have
666 a template like this:
667
668         { "String that ends in a newline.\n" }
669
670 The backslash inside the string is passed through to Perl unchanged,
671 so the C<\n> really does turn into a newline.  See the note at the end
672 for details about the way backslashes work.  Backslash processing is
673 I<not> done when you specify alternative delimiters with the
674 C<DELIMITERS> option.  (See L<"Alternative Delimiters">, below.)
675
676 Each program fragment should be a sequence of Perl statements, which
677 are evaluated the usual way.  The result of the last statement
678 executed will be evaluted in scalar context; the result of this
679 statement is a string, which is interpolated into the template in
680 place of the program fragment itself.
681
682 The fragments are evaluated in order, and side effects from earlier
683 fragments will persist into later fragments:
684
685         {$x = @things; ''}The Lord High Chamberlain has gotten {$x}
686         things for me this year.  
687         { $diff = $x - 17; 
688           $more = 'more'
689           if ($diff == 0) {
690             $diff = 'no';
691           } elsif ($diff < 0) {
692             $more = 'fewer';
693           } 
694           '';
695         } 
696         That is {$diff} {$more} than he gave me last year.
697
698 The value of C<$x> set in the first line will persist into the next
699 fragment that begins on the third line, and the values of C<$diff> and
700 C<$more> set in the second fragment will persist and be interpolated
701 into the last line.  The output will look something like this:
702
703         The Lord High Chamberlain has gotten 42
704         things for me this year.  
705
706         That is 25 more than he gave me last year.
707
708 That is all the syntax there is.  
709
710 =head2 The C<$OUT> variable
711
712 There is one special trick you can play in a template.  Here is the
713 motivation for it:  Suppose you are going to pass an array, C<@items>,
714 into the template, and you want the template to generate a bulleted
715 list with a header, like this:
716
717         Here is a list of the things I have got for you since 1907:
718           * Ivory
719           * Apes
720           * Peacocks
721           * ...
722
723 One way to do it is with a template like this:
724
725         Here is a list of the things I have got for you since 1907:
726         { my $blist = '';
727           foreach $i (@items) {
728             $blist .= qq{  * $i\n};
729           }    
730           $blist;
731         } 
732
733 Here we construct the list in a variable called C<$blist>, which we
734 return at the end.  This is a little cumbersome.  There is a shortcut.
735
736 Inside of templates, there is a special variable called C<$OUT>.
737 Anything you append to this variable will appear in the output of the
738 template.  Also, if you use C<$OUT> in a program fragment, the normal
739 behavior, of replacing the fragment with its return value, is
740 disabled; instead the fragment is replaced with the value of C<$OUT>.
741 This means that you can write the template above like this:
742
743         Here is a list of the things I have got for you since 1907:
744         { foreach $i (@items) {
745             $OUT .= "  * $i\n";
746           }    
747         } 
748
749 C<$OUT> is reinitialized to the empty string at the start of each
750 program fragment.  It is private to C<Text::Template>, so 
751 you can't use a variable named C<$OUT> in your template without
752 invoking the special behavior.
753
754 =head2 General Remarks
755
756 All C<Text::Template> functions return C<undef> on failure, and set the
757 variable C<$Text::Template::ERROR> to contain an explanation of what
758 went wrong.  For example, if you try to create a template from a file
759 that does not exist, C<$Text::Template::ERROR> will contain something like:
760
761         Couldn't open file xyz.tmpl: No such file or directory
762
763 =head2 C<new>
764
765         $template = new Text::Template ( TYPE => ..., SOURCE => ... );
766
767 This creates and returns a new template object.  C<new> returns
768 C<undef> and sets C<$Text::Template::ERROR> if it can't create the
769 template object.  C<SOURCE> says where the template source code will
770 come from.  C<TYPE> says what kind of object the source is.
771
772 The most common type of source is a file:
773
774         new Text::Template ( TYPE => 'FILE', SOURCE => $filename );
775
776 This reads the template from the specified file.  The filename is
777 opened with the Perl C<open> command, so it can be a pipe or anything
778 else that makes sense with C<open>.
779
780 The C<TYPE> can also be C<STRING>, in which case the C<SOURCE> should
781 be a string:
782
783         new Text::Template ( TYPE => 'STRING', 
784                              SOURCE => "This is the actual template!" );
785
786 The C<TYPE> can be C<ARRAY>, in which case the source should be a
787 reference to an array of strings.  The concatenation of these strings
788 is the template:
789
790         new Text::Template ( TYPE => 'ARRAY', 
791                              SOURCE => [ "This is ", "the actual", 
792                                          " template!",
793                                        ]
794                            );
795
796 The C<TYPE> can be FILEHANDLE, in which case the source should be an
797 open filehandle (such as you got from the C<FileHandle> or C<IO::*>
798 packages, or a glob, or a reference to a glob).  In this case
799 C<Text::Template> will read the text from the filehandle up to
800 end-of-file, and that text is the template:
801
802         # Read template source code from STDIN:
803         new Text::Template ( TYPE => 'FILEHANDLE', 
804                              SOURCE => \*STDIN  );
805
806
807 If you omit the C<TYPE> attribute, it's taken to be C<FILE>.
808 C<SOURCE> is required.  If you omit it, the program will abort.
809
810 The words C<TYPE> and C<SOURCE> can be spelled any of the following ways:
811
812         TYPE    SOURCE
813         Type    Source
814         type    source
815         -TYPE   -SOURCE
816         -Type   -Source
817         -type   -source
818
819 Pick a style you like and stick with it.
820
821 =over 4
822
823 =item C<DELIMITERS>
824
825 You may also add a C<DELIMITERS> option.  If this option is present,
826 its value should be a reference to an array of two strings.  The first
827 string is the string that signals the beginning of each program
828 fragment, and the second string is the string that signals the end of
829 each program fragment.  See L<"Alternative Delimiters">, below.
830
831 =item C<UNTAINT>
832
833 If your program is running in taint mode, you may have problems if
834 your templates are stored in files.  Data read from files is
835 considered 'untrustworthy', and taint mode will not allow you to
836 evaluate the Perl code in the file.  (It is afraid that a malicious
837 person might have tampered with the file.)
838
839 In some environments, however, local files are trustworthy.  You can
840 tell C<Text::Template> that a certain file is trustworthy by supplying
841 C<UNTAINT =E<gt> 1> in the call to C<new>.  This will tell
842 C<Text::Template> to disable taint checks on template code that has
843 come from a file, as long as the filename itself is considered
844 trustworthy.  It will also disable taint checks on template code that
845 comes from a filehandle.  When used with C<TYPE =E<gt> 'string'> or C<TYPE
846 =E<gt> 'array'>, it has no effect.
847
848 See L<perlsec> for more complete information about tainting.
849
850 Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr
851 for help with this feature.
852
853 =item C<PREPEND>
854
855 This option is passed along to the C<fill_in> call unless it is
856 overridden in the arguments to C<fill_in>.  See L<C<PREPEND> feature
857 and using C<strict> in templates> below.
858
859 =item C<BROKEN>
860
861 This option is passed along to the C<fill_in> call unless it is
862 overridden in the arguments to C<fill_in>.  See L<C<BROKEN>> below.
863
864 =back
865
866 =head2 C<compile>
867
868         $template->compile()
869
870 Loads all the template text from the template's source, parses and
871 compiles it.  If successful, returns true; otherwise returns false and
872 sets C<$Text::Template::ERROR>.  If the template is already compiled,
873 it returns true and does nothing.  
874
875 You don't usually need to invoke this function, because C<fill_in>
876 (see below) compiles the template if it isn't compiled already.
877
878 If there is an argument to this function, it must be a reference to an
879 array containing alternative delimiter strings.  See C<"Alternative
880 Delimiters">, below.
881
882 =head2 C<fill_in>
883
884         $template->fill_in(OPTIONS);
885
886 Fills in a template.  Returns the resulting text if successful.
887 Otherwise, returns C<undef>  and sets C<$Text::Template::ERROR>.
888
889 The I<OPTIONS> are a hash, or a list of key-value pairs.  You can
890 write the key names in any of the six usual styles as above; this
891 means that where this manual says C<PACKAGE> (for example) you can
892 actually use any of
893
894         PACKAGE Package package -PACKAGE -Package -package
895
896 Pick a style you like and stick with it.  The all-lowercase versions
897 may yield spurious warnings about
898
899         Ambiguous use of package => resolved to "package"
900
901 so you might like to avoid them and use the capitalized versions.
902
903 At present, there are eight legal options:  C<PACKAGE>, C<BROKEN>,
904 C<BROKEN_ARG>, C<SAFE>, C<HASH>, C<OUTPUT>, and C<DELIMITERS>.
905
906 =over 4
907
908 =item C<PACKAGE>
909
910 C<PACKAGE> specifies the name of a package in which the program
911 fragments should be evaluated.  The default is to use the package from
912 which C<fill_in> was called.  For example, consider this template:
913
914         The value of the variable x is {$x}.
915
916 If you use C<$template-E<gt>fill_in(PACKAGE =E<gt> 'R')> , then the C<$x> in
917 the template is actually replaced with the value of C<$R::x>.  If you
918 omit the C<PACKAGE> option, C<$x> will be replaced with the value of
919 the C<$x> variable in the package that actually called C<fill_in>.
920
921 You should almost always use C<PACKAGE>.  If you don't, and your
922 template makes changes to variables, those changes will be propagated
923 back into the main program.  Evaluating the template in a private
924 package helps prevent this.  The template can still modify variables
925 in your program if it wants to, but it will have to do so explicitly.
926 See the section at the end on `Security'.
927
928 Here's an example of using C<PACKAGE>:
929
930         Your Royal Highness,
931
932         Enclosed please find a list of things I have gotten
933         for you since 1907:
934
935         { foreach $item (@items) {
936             $item_no++;
937             $OUT .= " $item_no. \u$item\n";
938           }
939         }
940
941         Signed,
942         Lord High Chamberlain
943
944 We want to pass in an array which will be assigned to the array
945 C<@items>.  Here's how to do that:
946
947
948         @items = ('ivory', 'apes', 'peacocks', );
949         $template->fill_in();
950
951 This is not very safe.  The reason this isn't as safe is that if you
952 had a variable named C<$item_no> in scope in your program at the point
953 you called C<fill_in>, its value would be clobbered by the act of
954 filling out the template.  The problem is the same as if you had
955 written a subroutine that used those variables in the same way that
956 the template does.  (C<$OUT> is special in templates and is always
957 safe.)
958
959 One solution to this is to make the C<$item_no> variable private to the
960 template by declaring it with C<my>.  If the template does this, you
961 are safe.
962
963 But if you use the C<PACKAGE> option, you will probably be safe even
964 if the template does I<not> declare its variables with C<my>:
965
966         @Q::items = ('ivory', 'apes', 'peacocks', );
967         $template->fill_in(PACKAGE => 'Q');
968
969 In this case the template will clobber the variable C<$Q::item_no>,
970 which is not related to the one your program was using.
971
972 Templates cannot affect variables in the main program that are
973 declared with C<my>, unless you give the template references to those
974 variables.
975
976 =item C<HASH>
977
978 You may not want to put the template variables into a package.
979 Packages can be hard to manage:  You can't copy them, for example.
980 C<HASH> provides an alternative.  
981
982 The value for C<HASH> should be a reference to a hash that maps
983 variable names to values.  For example, 
984
985         $template->fill_in(HASH => { recipient => "The King",
986                                      items => ['gold', 'frankincense', 'myrrh'],
987                                      object => \$self,
988                                    });
989
990 will fill out the template and use C<"The King"> as the value of
991 C<$recipient> and the list of items as the value of C<@items>.  Note
992 that we pass an array reference, but inside the template it appears as
993 an array.  In general, anything other than a simple string or number
994 should be passed by reference.
995
996 We also want to pass an object, which is in C<$self>; note that we
997 pass a reference to the object, C<\$self> instead.  Since we've passed
998 a reference to a scalar, inside the template the object appears as
999 C<$object>.  
1000
1001 The full details of how it works are a little involved, so you might
1002 want to skip to the next section.
1003
1004 Suppose the key in the hash is I<key> and the value is I<value>.  
1005
1006 =over 4
1007
1008 =item *
1009
1010 If the I<value> is C<undef>, then any variables named C<$key>,
1011 C<@key>, C<%key>, etc., are undefined.  
1012
1013 =item *
1014
1015 If the I<value> is a string or a number, then C<$key> is set to that
1016 value in the template.
1017
1018 =item *
1019
1020 For anything else, you must pass a reference.
1021
1022 If the I<value> is a reference to an array, then C<@key> is set to
1023 that array.  If the I<value> is a reference to a hash, then C<%key> is
1024 set to that hash.  Similarly if I<value> is any other kind of
1025 reference.  This means that
1026
1027         var => "foo"
1028
1029 and
1030
1031         var => \"foo"
1032
1033 have almost exactly the same effect.  (The difference is that in the
1034 former case, the value is copied, and in the latter case it is
1035 aliased.)  
1036
1037 =item *
1038
1039 In particular, if you want the template to get an object or any kind,
1040 you must pass a reference to it:
1041
1042         $template->fill_in(HASH => { database_handle => \$dbh, ... });
1043
1044 If you do this, the template will have a variable C<$database_handle>
1045 which is the database handle object.  If you leave out the C<\>, the
1046 template will have a hash C<%database_handle>, which exposes the
1047 internal structure of the database handle object; you don't want that.
1048
1049 =back
1050
1051 Normally, the way this works is by allocating a private package,
1052 loading all the variables into the package, and then filling out the
1053 template as if you had specified that package.  A new package is
1054 allocated each time.  However, if you I<also> use the C<PACKAGE>
1055 option, C<Text::Template> loads the variables into the package you
1056 specified, and they stay there after the call returns.  Subsequent
1057 calls to C<fill_in> that use the same package will pick up the values
1058 you loaded in.
1059
1060 If the argument of C<HASH> is a reference to an array instead of a
1061 reference to a hash, then the array should contain a list of hashes
1062 whose contents are loaded into the template package one after the
1063 other.  You can use this feature if you want to combine several sets
1064 of variables.  For example, one set of variables might be the defaults
1065 for a fill-in form, and the second set might be the user inputs, which
1066 override the defaults when they are present:
1067
1068         $template->fill_in(HASH => [\%defaults, \%user_input]);
1069
1070 You can also use this to set two variables with the same name:
1071
1072         $template->fill_in(HASH => [{ v => "The King" },
1073                                     { v => [1,2,3] },
1074                                    ]
1075                           );
1076
1077 This sets C<$v> to C<"The King"> and C<@v> to C<(1,2,3)>.       
1078
1079 =item C<BROKEN>
1080
1081 If any of the program fragments fails to compile or aborts for any
1082 reason, and you have set the C<BROKEN> option to a function reference,
1083 C<Text::Template> will invoke the function.  This function is called
1084 the I<C<BROKEN> function>.  The C<BROKEN> function will tell
1085 C<Text::Template> what to do next.  
1086
1087 If the C<BROKEN> function returns C<undef>, C<Text::Template> will
1088 immediately abort processing the template and return the text that it
1089 has accumulated so far.  If your function does this, it should set a
1090 flag that you can examine after C<fill_in> returns so that you can
1091 tell whether there was a premature return or not. 
1092
1093 If the C<BROKEN> function returns any other value, that value will be
1094 interpolated into the template as if that value had been the return
1095 value of the program fragment to begin with.  For example, if the
1096 C<BROKEN> function returns an error string, the error string will be
1097 interpolated into the output of the template in place of the program
1098 fragment that cased the error.
1099
1100 If you don't specify a C<BROKEN> function, C<Text::Template> supplies
1101 a default one that returns something like
1102
1103         Program fragment delivered error ``Illegal division by 0 at
1104         template line 37''
1105
1106 (Note that the format of this message has changed slightly since
1107 version 1.31.)  The return value of the C<BROKEN> function is
1108 interpolated into the template at the place the error occurred, so
1109 that this template:
1110
1111         (3+4)*5 = { 3+4)*5 }
1112
1113 yields this result:
1114
1115         (3+4)*5 = Program fragment delivered error ``syntax error at template line 1''
1116
1117 If you specify a value for the C<BROKEN> attribute, it should be a
1118 reference to a function that C<fill_in> can call instead of the
1119 default function.
1120
1121 C<fill_in> will pass a hash to the C<broken> function.
1122 The hash will have at least these three members:
1123
1124 =over 4
1125
1126 =item C<text>
1127
1128 The source code of the program fragment that failed
1129
1130 =item C<error>
1131
1132 The text of the error message (C<$@>) generated by eval.
1133
1134 The text has been modified to omit the trailing newline and to include
1135 the name of the template file (if there was one).  The line number
1136 counts from the beginning of the template, not from the beginning of
1137 the failed program fragment.
1138
1139 =item C<lineno>
1140
1141 The line number of the template at which the program fragment began.
1142
1143 =back
1144
1145 There may also be an C<arg> member.  See C<BROKEN_ARG>, below
1146
1147 =item C<BROKEN_ARG>
1148
1149 If you supply the C<BROKEN_ARG> option to C<fill_in>, the value of the
1150 option is passed to the C<BROKEN> function whenever it is called.  The
1151 default C<BROKEN> function ignores the C<BROKEN_ARG>, but you can
1152 write a custom C<BROKEN> function that uses the C<BROKEN_ARG> to get
1153 more information about what went wrong. 
1154
1155 The C<BROKEN> function could also use the C<BROKEN_ARG> as a reference
1156 to store an error message or some other information that it wants to
1157 communicate back to the caller.  For example:
1158
1159         $error = '';
1160
1161         sub my_broken { 
1162            my %args = @_;
1163            my $err_ref = $args{arg};
1164            ...
1165            $$err_ref = "Some error message";
1166            return undef;
1167         }
1168
1169         $template->fill_in(BROKEN => \&my_broken,
1170                            BROKEN_ARG => \$error,
1171                           );
1172
1173         if ($error) {
1174           die "It didn't work: $error";
1175         }
1176
1177 If one of the program fragments in the template fails, it will call
1178 the C<BROKEN> function, C<my_broken>, and pass it the C<BROKEN_ARG>,
1179 which is a reference to C<$error>.  C<my_broken> can store an error
1180 message into C<$error> this way.  Then the function that called
1181 C<fill_in> can see if C<my_broken> has left an error message for it
1182 to find, and proceed accordingly.
1183
1184 =item C<SAFE>
1185
1186 If you give C<fill_in> a C<SAFE> option, its value should be a safe
1187 compartment object from the C<Safe> package.  All evaluation of
1188 program fragments will be performed in this compartment.  See L<Safe>
1189 for full details about such compartments and how to restrict the
1190 operations that can be performed in them.
1191
1192 If you use the C<PACKAGE> option with C<SAFE>, the package you specify
1193 will be placed into the safe compartment and evaluation will take
1194 place in that package as usual.  
1195
1196 If not, C<SAFE> operation is a little different from the default.
1197 Usually, if you don't specify a package, evaluation of program
1198 fragments occurs in the package from which the template was invoked.
1199 But in C<SAFE> mode the evaluation occurs inside the safe compartment
1200 and cannot affect the calling package.  Normally, if you use C<HASH>
1201 without C<PACKAGE>, the hash variables are imported into a private,
1202 one-use-only package.  But if you use C<HASH> and C<SAFE> together
1203 without C<PACKAGE>, the hash variables will just be loaded into the
1204 root namespace of the C<Safe> compartment.
1205
1206 =item C<OUTPUT>
1207
1208 If your template is going to generate a lot of text that you are just
1209 going to print out again anyway,  you can save memory by having
1210 C<Text::Template> print out the text as it is generated instead of
1211 making it into a big string and returning the string.  If you supply
1212 the C<OUTPUT> option to C<fill_in>, the value should be a filehandle.
1213 The generated text will be printed to this filehandle as it is
1214 constructed.  For example:
1215
1216         $template->fill_in(OUTPUT => \*STDOUT, ...);
1217
1218 fills in the C<$template> as usual, but the results are immediately
1219 printed to STDOUT.  This may result in the output appearing more
1220 quickly than it would have otherwise.
1221
1222 If you use C<OUTPUT>, the return value from C<fill_in> is still true on
1223 success and false on failure, but the complete text is not returned to
1224 the caller.
1225
1226 =item C<PREPEND>
1227
1228 You can have some Perl code prepended automatically to the beginning
1229 of every program fragment.  See L<C<PREPEND> feature and using
1230 C<strict> in templates> below.
1231
1232 =item C<DELIMITERS>
1233
1234 If this option is present, its value should be a reference to a list
1235 of two strings.  The first string is the string that signals the
1236 beginning of each program fragment, and the second string is the
1237 string that signals the end of each program fragment.  See
1238 L<"Alternative Delimiters">, below.  
1239
1240 If you specify C<DELIMITERS> in the call to C<fill_in>, they override
1241 any delimiters you set when you created the template object with
1242 C<new>. 
1243
1244 =back
1245
1246 =head1 Convenience Functions
1247
1248 =head2 C<fill_this_in>
1249
1250 The basic way to fill in a template is to create a template object and
1251 then call C<fill_in> on it.   This is useful if you want to fill in
1252 the same template more than once.
1253
1254 In some programs, this can be cumbersome.  C<fill_this_in> accepts a
1255 string, which contains the template, and a list of options, which are
1256 passed to C<fill_in> as above.  It constructs the template object for
1257 you, fills it in as specified, and returns the results.  It returns
1258 C<undef> and sets C<$Text::Template::ERROR> if it couldn't generate
1259 any results.
1260
1261 An example:
1262
1263         $Q::name = 'Donald';
1264         $Q::amount = 141.61;
1265         $Q::part = 'hyoid bone';
1266
1267         $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
1268         Dear {$name},
1269         You owe me \\${sprintf('%.2f', $amount)}.  
1270         Pay or I will break your {$part}.
1271                 Love,
1272                 Grand Vizopteryx of Irkutsk.
1273         EOM
1274
1275 Notice how we included the template in-line in the program by using a
1276 `here document' with the C<E<lt>E<lt>> notation.
1277
1278 C<fill_this_in> is a deprecated feature.  It is only here for
1279 backwards compatibility, and may be removed in some far-future version
1280 in C<Text::Template>.  You should use C<fill_in_string> instead.  It
1281 is described in the next section.
1282
1283 =head2 C<fill_in_string>
1284
1285 It is stupid that C<fill_this_in> is a class method.  It should have
1286 been just an imported function, so that you could omit the
1287 C<Text::Template-E<gt>> in the example above.  But I made the mistake
1288 four years ago and it is too late to change it.
1289
1290 C<fill_in_string> is exactly like C<fill_this_in> except that it is
1291 not a method and you can omit the C<Text::Template-E<gt>> and just say
1292
1293         print fill_in_string(<<'EOM', ...);
1294         Dear {$name},
1295           ...
1296         EOM
1297
1298 To use C<fill_in_string>, you need to say
1299
1300         use Text::Template 'fill_in_string';
1301
1302 at the top of your program.   You should probably use
1303 C<fill_in_string> instead of C<fill_this_in>.
1304
1305 =head2 C<fill_in_file>
1306
1307 If you import C<fill_in_file>, you can say
1308
1309         $text = fill_in_file(filename, ...);
1310
1311 The C<...> are passed to C<fill_in> as above.  The filename is the
1312 name of the file that contains the template you want to fill in.  It
1313 returns the result text. or C<undef>, as usual.
1314
1315 If you are going to fill in the same file more than once in the same
1316 program you should use the longer C<new> / C<fill_in> sequence instead.
1317 It will be a lot faster because it only has to read and parse the file
1318 once.
1319
1320 =head2 Including files into templates
1321
1322 People always ask for this.  ``Why don't you have an include
1323 function?'' they want to know.  The short answer is this is Perl, and
1324 Perl already has an include function.  If you want it, you can just put
1325
1326         {qx{cat filename}}
1327
1328 into your template.  VoilE<agrave>.
1329
1330 If you don't want to use C<cat>, you can write a little four-line
1331 function that opens a file and dumps out its contents, and call it
1332 from the template.  I wrote one for you.  In the template, you can say
1333
1334         {Text::Template::_load_text(filename)}
1335
1336 If that is too verbose, here is a trick.  Suppose the template package
1337 that you are going to be mentioning in the C<fill_in> call is package
1338 C<Q>.  Then in the main program, write
1339
1340         *Q::include = \&Text::Template::_load_text;
1341
1342 This imports the C<_load_text> function into package C<Q> with the
1343 name C<include>.  From then on, any template that you fill in with
1344 package C<Q> can say
1345
1346         {include(filename)}
1347
1348 to insert the text from the named file at that point.  If you are
1349 using the C<HASH> option instead, just put C<include =E<gt>
1350 \&Text::Template::_load_text> into the hash instead of importing it
1351 explicitly.
1352
1353 Suppose you don't want to insert a plain text file, but rather you
1354 want to include one template within another?  Just use C<fill_in_file>
1355 in the template itself:
1356
1357         {Text::Template::fill_in_file(filename)}
1358
1359 You can do the same importing trick if this is too much to type.
1360
1361 =head1 Miscellaneous
1362
1363 =head2 C<my> variables
1364
1365 People are frequently surprised when this doesn't work:
1366
1367         my $recipient = 'The King';
1368         my $text = fill_in_file('formletter.tmpl');
1369
1370 The text C<The King> doesn't get into the form letter.  Why not?
1371 Because C<$recipient> is a C<my> variable, and the whole point of
1372 C<my> variables is that they're private and inaccessible except in the
1373 scope in which they're declared.  The template is not part of that
1374 scope, so the template can't see C<$recipient>.  
1375
1376 If that's not the behavior you want, don't use C<my>.  C<my> means a
1377 private variable, and in this case you don't want the variable to be
1378 private.  Put the variables into package variables in some other
1379 package, and use the C<PACKAGE> option to C<fill_in>:
1380
1381         $Q::recipient = $recipient;
1382         my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
1383         
1384
1385 or pass the names and values in a hash with the C<HASH> option:
1386
1387         my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
1388
1389 =head2 Security Matters
1390
1391 All variables are evaluated in the package you specify with the
1392 C<PACKAGE> option of C<fill_in>.  if you use this option, and if your
1393 templates don't do anything egregiously stupid, you won't have to
1394 worry that evaluation of the little programs will creep out into the
1395 rest of your program and wreck something.
1396
1397 Nevertheless, there's really no way (except with C<Safe>) to protect
1398 against a template that says
1399
1400         { $Important::Secret::Security::Enable = 0; 
1401           # Disable security checks in this program 
1402         }
1403
1404 or
1405
1406         { $/ = "ho ho ho";   # Sabotage future uses of <FH>.
1407           # $/ is always a global variable
1408         }
1409
1410 or even
1411
1412         { system("rm -rf /") }
1413
1414 so B<don't> go filling in templates unless you're sure you know what's
1415 in them.  If you're worried, or you can't trust the person who wrote
1416 the template, use the C<SAFE> option.
1417
1418 A final warning: program fragments run a small risk of accidentally
1419 clobbering local variables in the C<fill_in> function itself.  These
1420 variables all have names that begin with C<$fi_>, so if you stay away
1421 from those names you'll be safe.  (Of course, if you're a real wizard
1422 you can tamper with them deliberately for exciting effects; this is
1423 actually how C<$OUT> works.)  I can fix this, but it will make the
1424 package slower to do it, so I would prefer not to.  If you are worried
1425 about this, send me mail and I will show you what to do about it.
1426
1427 =head2 Alternative Delimiters
1428
1429 Lorenzo Valdettaro pointed out that if you are using C<Text::Template>
1430 to generate TeX output, the choice of braces as the program fragment
1431 delimiters makes you suffer suffer suffer.  Starting in version 1.20,
1432 you can change the choice of delimiters to something other than curly
1433 braces.
1434
1435 In either the C<new()> call or the C<fill_in()> call, you can specify
1436 an alternative set of delimiters with the C<DELIMITERS> option.  For
1437 example, if you would like code fragments to be delimited by C<[@-->
1438 and C<--@]> instead of C<{> and C<}>, use
1439
1440         ... DELIMITERS => [ '[@--', '--@]' ], ...
1441
1442 Note that these delimiters are I<literal strings>, not regexes.  (I
1443 tried for regexes, but it complicates the lexical analysis too much.)
1444 Note also that C<DELIMITERS> disables the special meaning of the
1445 backslash, so if you want to include the delimiters in the literal
1446 text of your template file, you are out of luck---it is up to you to
1447 choose delimiters that do not conflict with what you are doing.  The
1448 delimiter strings may still appear inside of program fragments as long
1449 as they nest properly.  This means that if for some reason you
1450 absolutely must have a program fragment that mentions one of the
1451 delimiters, like this:
1452
1453         [@--
1454                 print "Oh no, a delimiter: --@]\n"
1455         --@]
1456
1457 you may be able to make it work by doing this instead:
1458
1459         [@--
1460                 # Fake matching delimiter in a comment: [@--
1461                 print "Oh no, a delimiter: --@]\n"
1462         --@]
1463
1464 It may be safer to choose delimiters that begin with a newline
1465 character.  
1466
1467 Because the parsing of templates is simplified by the absence of
1468 backslash escapes, using alternative C<DELIMITERS> may speed up the
1469 parsing process by 20-25%.  This shows that my original choice of C<{>
1470 and C<}> was very bad. 
1471
1472 =head2 C<PREPEND> feature and using C<strict> in templates
1473
1474 Suppose you would like to use C<strict> in your templates to detect
1475 undeclared variables and the like.  But each code fragment is a
1476 separate lexical scope, so you have to turn on C<strict> at the top of
1477 each and every code fragment:
1478
1479         { use strict;
1480           use vars '$foo';
1481           $foo = 14;
1482           ...
1483         }
1484
1485         ...
1486
1487         { # we forgot to put `use strict' here
1488           my $result = $boo + 12;    # $boo is misspelled and should be $foo
1489           # No error is raised on `$boo'
1490         }
1491
1492 Because we didn't put C<use strict> at the top of the second fragment,
1493 it was only active in the first fragment, and we didn't get any
1494 C<strict> checking in the second fragment.  Then we mispelled C<$foo>
1495 and the error wasn't caught.  
1496
1497 C<Text::Template> version 1.22 and higher has a new feature to make
1498 this easier.  You can specify that any text at all be automatically
1499 added to the beginning of each program fragment.  
1500
1501 When you make a call to C<fill_in>, you can specify a
1502
1503         PREPEND => 'some perl statements here'
1504
1505 option; the statements will be prepended to each program fragment for
1506 that one call only.  Suppose that the C<fill_in> call included a
1507
1508         PREPEND => 'use strict;'
1509
1510 option, and that the template looked like this:
1511
1512         { use vars '$foo';
1513           $foo = 14;
1514           ...
1515         }
1516
1517         ...
1518
1519         { my $result = $boo + 12;    # $boo is misspelled and should be $foo
1520           ...
1521         }
1522
1523 The code in the second fragment would fail, because C<$boo> has not
1524 been declared.  C<use strict> was implied, even though you did not
1525 write it explicitly, because the C<PREPEND> option added it for you
1526 automatically.
1527
1528 There are two other ways to do this.  At the time you create the
1529 template object with C<new>, you can also supply a C<PREPEND> option,
1530 in which case the statements will be prepended each time you fill in
1531 that template.  If the C<fill_in> call has its own C<PREPEND> option,
1532 this overrides the one specified at the time you created the
1533 template.  Finally, you can make the class method call
1534
1535         Text::Template->always_prepend('perl statements');
1536
1537 If you do this, then call calls to C<fill_in> for I<any> template will
1538 attach the perl statements to the beginning of each program fragment,
1539 except where overridden by C<PREPEND> options to C<new> or C<fill_in>.
1540
1541 =head2 Prepending in Derived Classes
1542
1543 This section is technical, and you should skip it on the first few
1544 readings. 
1545
1546 Normally there are three places that prepended text could come from.
1547 It could come from the C<PREPEND> option in the C<fill_in> call, from
1548 the C<PREPEND> option in the C<new> call that created the template
1549 object, or from the argument of the C<always_prepend> call.
1550 C<Text::Template> looks for these three things in order and takes the
1551 first one that it finds.
1552
1553 In a subclass of C<Text::Template>, this last possibility is
1554 ambiguous.  Suppose C<S> is a subclass of C<Text::Template>.  Should 
1555
1556         Text::Template->always_prepend(...);
1557
1558 affect objects in class C<Derived>?  The answer is that you can have it
1559 either way.  
1560
1561 The C<always_prepend> value for C<Text::Template> is normally stored
1562 in  a hash variable named C<%GLOBAL_PREPEND> under the key
1563 C<Text::Template>.  When C<Text::Template> looks to see what text to
1564 prepend, it first looks in the template object itself, and if not, it
1565 looks in C<$GLOBAL_PREPEND{I<class>}> where I<class> is the class to
1566 which the template object belongs.  If it doesn't find any value, it
1567 looks in C<$GLOBAL_PREPEND{'Text::Template'}>.  This means that
1568 objects in class C<Derived> I<will> be affected by
1569
1570         Text::Template->always_prepend(...);
1571
1572 I<unless> there is also a call to
1573
1574         Derived->always_prepend(...);
1575
1576 So when you're designing your derived class, you can arrange to have
1577 your objects ignore C<Text::Template::always_prepend> calls by simply
1578 putting C<Derived-E<gt>always_prepend('')> at the top of your module.
1579
1580 Of course, there is also a final escape hatch: Templates support a
1581 C<prepend_text> that is used to look up the appropriate text to be
1582 prepended at C<fill_in> time.  Your derived class can override this
1583 method to get an arbitrary effect.
1584
1585 =head2 JavaScript
1586
1587 Jennifer D. St Clair asks:
1588
1589         > Most of my pages contain JavaScript and Stylesheets.
1590         > How do I change the template identifier?  
1591
1592 Jennifer is worried about the braces in the JavaScript being taken as
1593 the delimiters of the Perl program fragments.  Of course, disaster
1594 will ensue when perl tries to evaluate these as if they were Perl
1595 programs.  The best choice is to find some unambiguous delimiter
1596 strings that you can use in your template instead of curly braces, and
1597 then use the C<DELIMITERS> option.  However, if you can't do this for
1598 some reason, there are  two easy workarounds:
1599
1600 1. You can put C<\> in front of C<{>, C<}>, or C<\> to remove its
1601 special meaning.  So, for example, instead of
1602
1603             if (br== "n3") { 
1604                 // etc.
1605             }
1606
1607 you can put
1608
1609             if (br== "n3") \{ 
1610                 // etc.
1611             \}
1612
1613 and it'll come out of the template engine the way you want.
1614
1615 But here is another method that is probably better.  To see how it
1616 works, first consider what happens if you put this into a template:
1617
1618             { 'foo' }
1619
1620 Since it's in braces, it gets evaluated, and obviously, this is going
1621 to turn into
1622
1623             foo
1624
1625 So now here's the trick: In Perl, C<q{...}> is the same as C<'...'>.
1626 So if we wrote
1627
1628             {q{foo}}
1629
1630 it would turn into 
1631
1632             foo
1633
1634 So for your JavaScript, just write
1635
1636             {q{if (br== "n3") { 
1637                  // etc.
1638                }}
1639             }
1640
1641 and it'll come out as
1642
1643               if (br== "n3") { 
1644                   // etc.
1645               }
1646
1647 which is what you want.
1648
1649
1650 =head2 Shut Up!
1651
1652 People sometimes try to put an initialization section at the top of
1653 their templates, like this:
1654
1655         { ...
1656           $var = 17;
1657         }
1658
1659 Then they complain because there is a C<17> at the top of the output
1660 that they didn't want to have there.  
1661
1662 Remember that a program fragment is replaced with its own return
1663 value, and that in Perl the return value of a code block is the value
1664 of the last expression that was evaluated, which in this case is 17.
1665 If it didn't do that, you wouldn't be able to write C<{$recipient}>
1666 and have the recipient filled in.
1667
1668 To prevent the 17 from appearing in the output is very simple:
1669
1670         { ...
1671           $var = 17;
1672           '';
1673         }
1674
1675 Now the last expression evaluated yields the empty string, which is
1676 invisible.  If you don't like the way this looks, use
1677
1678         { ...
1679           $var = 17;
1680           ($SILENTLY);
1681         }
1682
1683 instead.  Presumably, C<$SILENTLY> has no value, so nothing will be
1684 interpolated.  This is what is known as a `trick'.
1685
1686 =head2 Compatibility
1687
1688 Every effort has been made to make this module compatible with older
1689 versions.  The only known exceptions follow:
1690
1691 The output format of the default C<BROKEN> subroutine has changed
1692 twice, most recently between versions 1.31 and 1.40.
1693
1694 Starting in version 1.10, the C<$OUT> variable is arrogated for a
1695 special meaning.  If you had templates before version 1.10 that
1696 happened to use a variable named C<$OUT>, you will have to change them
1697 to use some other variable or all sorts of strangeness will result.
1698
1699 Between versions 0.1b and 1.00 the behavior of the \ metacharacter
1700 changed.  In 0.1b, \\ was special everywhere, and the template
1701 processor always replaced it with a single backslash before passing
1702 the code to Perl for evaluation.  The rule now is more complicated but
1703 probably more convenient.  See the section on backslash processing,
1704 below, for a full discussion.
1705
1706 =head2 Backslash Processing
1707
1708 In C<Text::Template> beta versions, the backslash was special whenever
1709 it appeared before a brace or another backslash.  That meant that
1710 while C<{"\n"}> did indeed generate a newline, C<{"\\"}> did not
1711 generate a backslash, because the code passed to Perl for evaluation
1712 was C<"\"> which is a syntax error.  If you wanted a backslash, you
1713 would have had to write C<{"\\\\"}>.
1714
1715 In C<Text::Template> versions 1.00 through 1.10, there was a bug:
1716 Backslash was special everywhere.  In these versions, C<{"\n"}>
1717 generated the letter C<n>.
1718
1719 The bug has been corrected in version 1.11, but I did not go back to
1720 exactly the old rule, because I did not like the idea of having to
1721 write C<{"\\\\"}> to get one backslash.  The rule is now more
1722 complicated to remember, but probably easier to use.  The rule is now:
1723 Backslashes are always passed to Perl unchanged I<unless> they occur
1724 as part of a sequence like C<\\\\\\{> or C<\\\\\\}>.  In these
1725 contexts, they are special; C<\\> is replaced with C<\>, and C<\{> and
1726 C<\}> signal a literal brace. 
1727
1728 Examples:
1729
1730         \{ foo \}
1731
1732 is I<not> evaluated, because the C<\> before the braces signals that
1733 they should be taken literally.  The result in the output looks like this: 
1734
1735         { foo }
1736
1737
1738 This is a syntax error:
1739
1740         { "foo}" }
1741
1742 because C<Text::Template> thinks that the code ends at the first C<}>,
1743 and then gets upset when it sees the second one.  To make this work
1744 correctly, use
1745
1746         { "foo\}" }
1747
1748 This passes C<"foo}"> to Perl for evaluation.  Note there's no C<\> in
1749 the evaluated code.  If you really want a C<\> in the evaluated code,
1750 use
1751
1752         { "foo\\\}" }
1753
1754 This passes C<"foo\}"> to Perl for evaluation.
1755
1756 Starting with C<Text::Template> version 1.20, backslash processing is
1757 disabled if you use the C<DELIMITERS> option to specify alternative
1758 delimiter strings.
1759
1760 =head2 A short note about C<$Text::Template::ERROR>
1761
1762 In the past some people have fretted about `violating the package
1763 boundary' by examining a variable inside the C<Text::Template>
1764 package.  Don't feel this way.  C<$Text::Template::ERROR> is part of
1765 the published, official interface to this package.  It is perfectly OK
1766 to inspect this variable.  The interface is not going to change.
1767
1768 If it really, really bothers you, you can import a function called
1769 C<TTerror> that returns the current value of the C<$ERROR> variable.
1770 So you can say:
1771
1772         use Text::Template 'TTerror';
1773
1774         my $template = new Text::Template (SOURCE => $filename);
1775         unless ($template) {
1776           my $err = TTerror;
1777           die "Couldn't make template: $err; aborting";
1778         }
1779
1780 I don't see what benefit this has over just doing this:
1781
1782         use Text::Template;
1783
1784         my $template = new Text::Template (SOURCE => $filename)
1785           or die "Couldn't make template: $Text::Template::ERROR; aborting";
1786
1787 But if it makes you happy to do it that way, go ahead.
1788
1789 =head2 Sticky Widgets in Template Files
1790
1791 The C<CGI> module provides functions for `sticky widgets', which are
1792 form input controls that retain their values from one page to the
1793 next.   Sometimes people want to know how to include these widgets
1794 into their template output.
1795
1796 It's totally straightforward.  Just call the C<CGI> functions from
1797 inside the template:
1798
1799         { $q->checkbox_group(NAME => 'toppings',
1800                              LINEBREAK => true,
1801                              COLUMNS => 3,
1802                              VALUES => \@toppings,
1803                             );
1804         }
1805
1806 =head2 Automatic preprocessing of program fragments
1807
1808 It may be useful to preprocess the program fragments before they are
1809 evaluated.  See C<Text::Template::Preprocess> for more details.
1810
1811 =head2 Automatic postprocessing of template hunks
1812
1813 It may be useful to process hunks of output before they are appended to
1814 the result text.  For this, subclass and replace the C<append_text_to_result>
1815 method.  It is passed a list of pairs with these entries:
1816
1817   handle - a filehandle to which to print the desired output
1818   out    - a ref to a string to which to append, to use if handle is not given
1819   text   - the text that will be appended
1820   type   - where the text came from: TEXT for literal text, PROG for code
1821
1822 =head2 Author
1823
1824 Mark Jason Dominus, Plover Systems
1825
1826 Please send questions and other remarks about this software to
1827 C<mjd-perl-template+@plover.com>
1828
1829 You can join a very low-volume (E<lt>10 messages per year) mailing
1830 list for announcements about this package.  Send an empty note to
1831 C<mjd-perl-template-request@plover.com> to join.
1832
1833 For updates, visit C<http://www.plover.com/~mjd/perl/Template/>.
1834
1835 =head2 Support?
1836
1837 This software is version 1.46.  It may have bugs.  Suggestions and bug
1838 reports are always welcome.  Send them to
1839 C<mjd-perl-template+@plover.com>.  (That is my address, not the address
1840 of the mailing list.  The mailing list address is a secret.)
1841
1842 =head1 LICENSE
1843
1844     Text::Template version 1.46
1845     Copyright 2013 Mark Jason Dominus
1846
1847     This program is free software; you can redistribute it and/or
1848     modify it under the terms of the GNU General Public License as
1849     published by the Free Software Foundation; either version 2 of the
1850     License, or (at your option) any later version.  You may also can
1851     redistribute it and/or modify it under the terms of the Perl
1852     Artistic License.
1853
1854     This program is distributed in the hope that it will be useful,
1855     but WITHOUT ANY WARRANTY; without even the implied warranty of
1856     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1857     GNU General Public License for more details.
1858
1859     You should have received copies of the GNU General Public License
1860     along with this program; if not, write to the Free Software
1861     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
1862
1863
1864 =head1 THANKS
1865
1866 Many thanks to the following people for offering support,
1867 encouragement, advice, bug reports, and all the other good stuff.  
1868
1869 David H. Adler /
1870 Joel Appelbaum /
1871 Klaus Arnhold /
1872 AntE<oacute>nio AragE<atilde>o /
1873 Kevin Atteson /
1874 Chris.Brezil /
1875 Mike Brodhead /
1876 Tom Brown /
1877 Dr. Frank Bucolo /
1878 Tim Bunce /
1879 Juan E. Camacho /
1880 Itamar Almeida de Carvalho /
1881 Joseph Cheek /
1882 Gene Damon /
1883 San Deng /
1884 Bob Dougherty /
1885 Marek Grac /
1886 Dan Franklin /
1887 gary at dls.net /
1888 Todd A. Green /
1889 Donald L. Greer Jr. /
1890 Michelangelo Grigni /
1891 Zac Hansen /
1892 Tom Henry /
1893 Jarko Hietaniemi /
1894 Matt X. Hunter /
1895 Robert M. Ioffe /
1896 Daniel LaLiberte /
1897 Reuven M. Lerner /
1898 Trip Lilley / 
1899 Yannis Livassof /
1900 Val Luck /
1901 Kevin Madsen /
1902 David Marshall /
1903 James Mastros /
1904 Joel Meulenberg /
1905 Jason Moore /
1906 Sergey Myasnikov /
1907 Chris Nandor /
1908 Bek Oberin /
1909 Steve Palincsar /
1910 Ron Pero /
1911 Hans Persson /
1912 Sean Roehnelt /
1913 Jonathan Roy /
1914 Shabbir J. Safdar /
1915 Jennifer D. St Clair /
1916 Uwe Schneider /
1917 Randal L. Schwartz /
1918 Michael G Schwern /
1919 Yonat Sharon /
1920 Brian C. Shensky /
1921 Niklas Skoglund /
1922 Tom Snee /
1923 Fred Steinberg /
1924 Hans Stoop /
1925 Michael J. Suzio /
1926 Dennis Taylor /
1927 James H. Thompson /
1928 Shad Todd /
1929 Lieven Tomme /
1930 Lorenzo Valdettaro /
1931 Larry Virden /
1932 Andy Wardley /
1933 Archie Warnock /
1934 Chris Wesley /
1935 Matt Womer /
1936 Andrew G Wood /
1937 Daini Xie /
1938 Michaely Yeung
1939
1940 Special thanks to:
1941
1942 =over 2
1943
1944 =item Jonathan Roy 
1945
1946 for telling me how to do the C<Safe> support (I spent two years
1947 worrying about it, and then Jonathan pointed out that it was trivial.)
1948
1949 =item Ranjit Bhatnagar 
1950
1951 for demanding less verbose fragments like they have in ASP, for
1952 helping me figure out the Right Thing, and, especially, for talking me
1953 out of adding any new syntax.  These discussions resulted in the
1954 C<$OUT> feature.
1955
1956 =back
1957
1958 =head2 Bugs and Caveats
1959
1960 C<my> variables in C<fill_in> are still susceptible to being clobbered
1961 by template evaluation.  They all begin with C<fi_>, so avoid those
1962 names in your templates.
1963
1964 The line number information will be wrong if the template's lines are
1965 not terminated by C<"\n">.  You should let me know if this is a
1966 problem.  If you do, I will fix it.
1967
1968 The C<$OUT> variable has a special meaning in templates, so you cannot
1969 use it as if it were a regular variable.
1970
1971 There are not quite enough tests in the test suite.
1972
1973 =cut