Subbeh
Subbeh

Reputation: 924

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:

x=1+${emptyVar:-0}

I am looking for something similar as this

Upvotes: 3

Views: 330

Answers (1)

Tanktalus
Tanktalus

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

Related Questions