Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Template with strict option: how to check whether a variable is defined?

Tags:

perl

The following code dies with a var.undef error because var is not defined. It works if I change the STRICT option to 0, but I'd like to keep strict checks, unless it's in an [% IF var %] check in the template. How do I do that?

use strict;
use warnings;
use Template;

my $t = Template->new(STRICT => 1) || die Template->error();
my $template = '[% IF var %][% var %][% END%]';
my $output = '';
$t->process(\$template, {}, \$output) || die $t->error(), "\n";
print "$output\n";
like image 275
Robert Avatar asked Jan 31 '26 21:01

Robert


1 Answers

You are sending in an empty hash reference that doesn't contain the var variable that you're asking the template to display.

You can either check in your Perl code to set a sane default (in this example, I just hard-code it into the call to process()):

$t->process(\$template, {var => 55}, $output) || die $t->error(), "\n";

Output:

55

...or, you can tell the template to set its own sane default if the var variable isn't sent on the way in (ie, it's undefined):

my $template = '[% DEFAULT var = "sane" %][% IF var %][% var %][% END%]';

Output:

sane
like image 80
stevieb Avatar answered Feb 03 '26 11:02

stevieb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!