3

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! Exactly what I was looking for
the question says undefined or empty string, so $x = 1 + ($emptyVar || 0); instead
@ysth - true, though when likening to shell where "empty" and "undef" are largely indistinguishable, I figured there was a good chance that's what OP meant.
++($x = $emptyVar)
I find the defined-or useful in case like: exit 0 if (fork // -1) -- otherwise I cannot distinguish between fork failing (unlikely but possible) and child process. tried with strace -f -e trace=process perl -le 'print "foo" if (fork // -1)' to see this may be useful...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.