Basically I want to get user input and decide what to do, and I need to have the same outcome even for different user inputs sometimes. Example code:
given ($command) {
when ('a' || 'add') {add}
when ('s' || 'subtract') {subtract}
when ('m' || 'multiply') {multiply}
when ('d' || 'divide') {divide}
default { print "try again, usage: add, subtract, multiply, divide (a, s, m, d)\n" }
Now the trouble with this is that it only works if I type the single letter commands at the beginning of the or statements. If I type something like “add” into the prompt, I get the default message telling me to try again.
I could make separate cases for these, but it would just have the same body as the single letters, which is just redundant.
The
given/whenconstruct uses the smart match operator, which doesn’t have any special-case behavior for the||operator. The expressionevaluates to
'a', so it just matches$commandagainst the string'a'.If you want to match
$commandagainst any of a list of values, you can use an array value:(As usual, there are several ways to express this.)
References:
perldoc -f givenperldoc perlsyn; search for “Switch statements” and “Smart matching in detail”.EDIT :
Another approach for this problem, if you want to allow
$commandto be any prefix of the command name (e.g.,"s","su","sub", …,"subtract") is something like this: