LPM: Problems with text::template

David Hempy hempy at ket.org
Wed Jun 21 21:12:29 CDT 2000


At 09:50 PM 6/21/2000 -0400, you wrote:
>So are you suggesting that my template should look more like this:
>
><!-- Begin News Text -->
>Get news here:  {$news=&getnews;print $news;''}
></td>
><!-- End News Text -->


No...you had the template just right:


<!-- Begin News Text -->
Get news here:  {&getnews;}
</td>
<!-- End News Text -->



I'm guessing your sub currently looks something like this:

sub getnews {
         my ($news) = "Just another perl hacker";
         print $news;
}

It should look more like this:

sub getnews {
         my ($news) = "Just another perl hacker";
         return $news;
}



When Text::Template evaluates the contents of {...}, it (usually*) takes 
the result of that expression and substitutes it in the final 
output.  After it is done processing the whole template, including all 
embedded expressions, it returns the grand product back to you for you to 
print or save or otherwise admire (unless you told it to send it somewhere 
else, like STDOUT).

So, if you go print stuff in your subroutine before Text::Template 
completes its thing, your subroutine's output will be printed long before 
the template's output is even ready to be printed.


Hope this helps,
-dave

-----

* The expression's return value is discarded by Text::Template if you use 
the variable $OUT in the expression.  If $OUT has a value, it is included 
in the output instead of the return value.  This lets you be lazy and say:

{
         foreach $gift (sort keys %gifts) {
                 $OUT .= "Thanks for the $gift.<br>";
         }
}

...instead of:

{
         my $thanks;

         foreach $gift (sort keys %gifts) {
                 $thanks .= "Thanks for the $gift.<br>";
         }

         return $thanks;
}

This alleviates you from having to say "my $thanks" and leave the "return 
$thanks;".  This comes up often enough when you have a loop in your code 
that it is really handy.





--
David Hempy
Internet Database Administrator
Kentucky Educational Television
<hempy at ket.org> -- (606)258-7164 -- (800)333-9764





More information about the Lexington-pm mailing list