Search code examples
perltemplate-toolkit

Error while using un-initialized variable in an expression in a template file


I am trying to process a template file using template-toolkit version 2.29 and perl 5.28.1. I am getting below warning while processing template file
Argument "" isn't numeric in addition (+) at line xyz
I think it is because in the template file we have un-initialized variables which are used in an arithmetic expression.
Is it necessary to initialize a variable before using it in an expression if using template-toolkit version 2.29? In the below code the warning occurs for line 5.

Below is the snippet from code.

[%- groups = {} -%] <br/>
[%- cols = [ 10, 10, 20, 30 ] -%] <br/>
[%- FOREACH c IN cols -%] <br/>
   [%- val = c -%] <br/>
   [%- groups.$val = groups.$val + 1 -%] <br/>
[%- END -%] <br/>

If we initialize groups.$val before using it in the expression, there is no warning.
I did not get the issue when I used template-toolkit version 2.15. Not sure what changed in 2.29 (or in any other version greater than 2.15) which is causing the warning?


Solution

  • It's not an error, it's a warning.

    If you don't want to get the warnings, just populate the variable when assigning to it:

    [%- groups.$val = (groups.$val || 0) + 1 -%]
    

    or maybe

    [%- groups.$val = (groups.$val.defined ? groups.$val : 0) + 1 -%]
    

    Unfortunately, there's no operator similar to Perl's ++ or += that would skip the warnings as the Perl's operators do.