Perl pattern with strict variant: how to check if a variable is defined?
The following code dies with the var.undef error because it is var
not defined. It works if I change the parameter STRICT
to 0, but I would like to keep the strict checks, unless [% IF var %]
it checks the template. How to do it?
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";
source to share
You are submitting an empty hash link that does not contain the variable var
you are requesting to render the template.
You can either check your Perl code to set the default to a standard setting (in this example, I'll just recode the code into a call process()
):
$t->process(\$template, {var => 55}, $output) || die $t->error(), "\n";
Output:
55
... or you can tell the template to set its own normal default if the variable is var
not posted on the path (i.e. it's undefined):
my $template = '[% DEFAULT var = "sane" %][% IF var %][% var %][% END%]';
Output:
sane
source to share