Subbeh Subbeh - 8 months ago 80
Perl Question

Perl - use 0 if string is empty

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:


I am looking for something similar as this

Answer Source

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.