Bad slipup with ternary operators

Posted By on September 1, 2011

I’m a fan of ternary operators. I’ve seen some people complain that they make code less readable but I don’t agree. I suppose it’s fair to say it’s not as plain to scan through but I think any decent programmer should understand them. The other day, however, I came across a legacy one in our ETL process that was not doing the right job.

One section of our ETL loads in a bunch of values that, if null, are supposed to be set to hyphens. ( There’s some reason for this absurdity that relates to 3rd parties, but we’ll not get into that.) These values are sent to a perl function that validates and assigns them with the following ternary operation:

push @values, $value ? $value : "-";

Can you guess the problem?

In the majority of cases this works perfectly. A null or undefined value will evaluate as false and the hyphen will return. Unfortunately, sometimes this value can be 0, and Perl, being the way it is, will evaluate that as false too!

It was a pretty obvious bug when I found it. In essence this is not asking the right question. We don’t want to know if $value is true or false, we want to know if it’s defined. The fix is extremely simple:

push @values, defined($value) ? $value : "-";

About the author

Comments

Leave a Reply