not $x respecting numeric 0

P

peter pilsl

I look for an shorter version of for:

if (defined $x and $x ne '') { ...}


One of my most frequent programm-bugs is that I often include statements
like:

if ($x) { ...}

which skips the block, if $x is undefined, empty or has the value 0.

And the latter is my problem: I would like to have a
as-simple-as-possible-statment that checks if $x is undefined or '' but
returns true if the value is 0, cause 0 is a perfect normal value in
most of my applications. Is there kind of a "numeric-aware" not-operator?

thnx,
peter
 
A

Anno Siegel

peter pilsl said:
I look for an shorter version of for:

if (defined $x and $x ne '') { ...}


One of my most frequent programm-bugs is that I often include statements
like:

if ($x) { ...}

which skips the block, if $x is undefined, empty or has the value 0.

And the latter is my problem: I would like to have a
as-simple-as-possible-statment that checks if $x is undefined or '' but
returns true if the value is 0, cause 0 is a perfect normal value in
most of my applications. Is there kind of a "numeric-aware" not-operator?

If $x happens to be in $_, "defined and length" is a bit shorter, otherwise
there isn't a whole lot you can do about it.

Anno
 
P

phaylon

peter said:
I would like to have a as-simple-as-possible-statment that checks if $x
is undefined or '' but returns true if the value is 0, cause 0 is a
perfect normal value in most of my applications. Is there kind of a
"numeric-aware" not-operator?

Hm. I would say: Make a function that does this. Sorry, don't know
anything else.
 
A

Anno Siegel

Anno Siegel said:
peter pilsl said:
I look for an shorter version of for:

if (defined $x and $x ne '') { ...}
[...]

If $x happens to be in $_, "defined and length" is a bit shorter, otherwise
there isn't a whole lot you can do about it.

Come to think of it, if we already had the err operator, this would do:

length( $x err '');

Anno
 
J

jilerner

You essentially ask 'how to make the condition in if() look
simpler/shorter'.

One answer is:
if(!Empty($x)) { ... }

where Empty() is defined as
sub Empty { return ! defined($_[0]) || $_[0] eq ''; }

Another possibility (in your specific case where you treat
undef and '' same way ) would be make sure your
variables are not undefined:

$x = '' if !defined($x);
...
if( $x ne '') ...

YL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top