Better Living Through Thinking

Using Perl's Ternary Operator as a Switch/Case Statement

Wed, 18 Oct 2006

I'm certain someone has already come up with this, but I was recently refactoring some old code that looked like this:

my $code = get_error_code();
my $why;
if ($code == 1) {
  $why = "Invalid characters";
} elsif ($code == 2) {
  $why = "Unknown Domain";
} elsif ($code == 3) {
  $why = "Timeout";
} elsif ($code == 4) {
  $why = "Unknown User";
} elsif ($code == 5) {
  $why = "Slow Server";
} elsif ($code == 6) {
  $why = "Down Server";
} elsif ($code == 7) {
  $why = "Server Full";
} else {
  $why = "Unknown failure";
}

I changed it to look like this (in emacs's perl-mode, but any editor will do):

my $code = get_error_code();
my $why
    = $code == 1 ? "Invalid characters"
    : $code == 2 ? "Unknown Domain"
    : $code == 3 ? "Timeout"
    : $code == 4 ? "Unknown User"
    : $code == 5 ? "Slow Server"
    : $code == 6 ? "Down Server"
    : $code == 7 ? "Server Full"
    :              "Unknown failure";

I think most people would agree it's far more readable and concise (at less than half the lines).

[ category: /perl | link: ternary_switch ]

Audio Broadcast

(standby)

Moon Status

Phase: 99.97%
Illuminated: 0.00%
Age (days): 29.52
moon phase 0.999735477305503 Sun May 20 17:36:33 MDT 2012