11/17

6. Cascading Ifs (Chapter 6)

  • Cascading ifs are bad:

        if (condition) {
    	$value = foo;
        } 
        elsif (condition) {
    	$value = bar;
        }
        elsif (...) {
    	$value = baz;
        }
  • You may be able to replace with a table lookup:

        my %hash = (
    	...
        );
        if (defined $hash{value}) {
    	$value = $hash{value};
        }
  • Or a tabular ternary:

        my $salute = $name eq $EMPTY_STR                       ? 'Dear Customer'
    	       ? $name =~ m/ \A((?:Sir|Dame) \s+ \S+) /xms ? "Dear $1"
    	       ? $name =~ m/ (.*), \s+ Ph[.]?D \z     /xms ? "Dear Dr $1"
    	       :                                             "Dear $name"