Perl has no switch statements. How do I avoid a long if-else-if pattern?
The problem:
You have some conditional behaviour that depends on the value of a variable, for example, a user’s selection of a menu.
Solution: Hashes!
A neat way to avoid the problem is to use a hash.
Use subroutine references in a hash to define what to do for each case:
Then where your if statements would be, simply call the subroutine:
While for this small example, the amount of code saved is not staggering, to include extra cases you only need to add entries to the ‘action_to_take’ hash, rather than create a whole new section to the if statement.
It also means that you can build the hash in another subroutine and call it somewhere else.
The full example follows: