|Syntactic Confectionery Delight|
Re: Given When Syntaxby Laurent_R (Canon)
|on Mar 15, 2014 at 16:39 UTC||Need Help??|
The switch (given/when) feature is an experimental feature that should probably be avoided.
From the Perl documentation ( http://perldoc.perl.org/perlsyn.html#Experimental-Details-on-given-and-when) : As previously mentioned, the "switch" feature is considered highly experimental; it is subject to change with little notice. In particular, when has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. Before Perl 5.18, given also had tricky behaviours that you should still beware of if your code must run on older versions of Perl.
It is probably not wise to use this feature for anything else than a one-off program that you know will never have to be used again in the future, as your syntax might break in the next Perl version.
Using an array is probably the simplest alternative for your very simple case:
If your actual case is more complicated, then a hash might be the solution:
For more complicated things, such as taking actions on the basis of the value of a variable, you might want to use a dispatch table (essentially a hash in which the values are references to subs). For example, the following is using a long list of if /elsif expressions to determine what series of actions to do depending on some parameters received as arguments:
You could replace this with the following dispatch table:
and use it as follows:
If even that is not OK, then you can also go for either the for/if constructs referred to in the link provided by LanX above (http://www.perlmonks.org/?node_id=826710) or, if worse come to worse, to the series of if/elsif.