Main Content

Setting a safety net or fallback value in Perl

Archive - Originally posted on "The Horse's Mouth" - 2010-06-19 06:33:23 - Graham Ellis

Let's say that you want a Perl variable to contain a result which varies depending in the type and values of data fed in. Easy enough - but you need to think about what value you want it to hold if the inputs don't match any of the acceptable values. And there are then two approaches:

1. You can set a Perl variable to a default value early in the code, then override it if you find a matching type and value entered by the user.

2. You can set the variable if you find matching data, and then conclude your code with a "safety net" assignment to set a fallback value if nothing matched at all:
  $name ||= "[Not identified. Not usual colours]";

If you're using the second method, though, you need to take care if an empty string or zero (a false value) is a valid matched value, and you should really rewrite your code:
  defined ($name) or $name = "[Not identified. Not usual colours]";

From Perl 5.10 onwards, a new operator - // - is provided to provide you with a shorthand for "defined or", and you can now write:
  $name //= "[Not identified. Not usual colours]";

We have provided a complete example - [source code here].