Wednesday, January 14, 2015

Old Dog Learns New Trick: The NCO

While learning Swift I came across something to which I was not accustomed: the Nil Coalescing Operator.


For example:
optionalValue ?? valueIfNil

Which more or less translates to: "The value of optionalValue unless it isn't defined, in which case default to valueIfNil"

Usually this would be written as:
(optionalValue != nil) ? optionalValue! : valueIfNil;

I liked what I saw & looked into it and to my surprise it also exists in perl as the Null Coalescing Operator / Logical Defined-Or operator.

In perl the above example is rewritten as:

$optional_value // $value_if_null

Which is in turn shorthand for:
defined($optional_value) ? $optional_value : $value_if_null

However there is more - because in perl there is a shorthand notation for this:
$optional_value //= $value_if_null
  
Which is the equivalent of:
$optional_value = $optional_value // $value_if_null

No comments:

Post a Comment