Reputation: 924
When using arithmetic expressions in combination with an undefined or empty string, perl throws an error. Is there a clean way to use zero in case a string is empty?
This does not work:
$x = 1 + $emptyVar
In bash you could use something like this for instance to use zero if the variable $emptyVar is empty:
x=1+${emptyVar:-0}
I am looking for something similar as this
Upvotes: 3
Views: 330
Reputation: 22254
There are many ways to do this. e.g.:
$x = $emptyVar;
$x += 1;
or maybe:
$x = 1 + ($emptyVar // 0); # defined-or operator
or maybe:
{
no warnings 'uninitialized';
$x = 1 + $emptyVar;
}
Of these, I usually use the second one. If the level of perl I'm using doesn't have defined-or, then a simple or (||
) works fine, too.
Upvotes: 5