2 ms·
given/when isn't a switch statement. given and when are two separate constructs that happen to work well together for switch-statement-style purposes. given te
by ekiru 16y ago
given/when isn't a switch statement. given and when are two separate constructs that happen to work well together for switch-statement-style purposes.
given temporarily sets the topic($_) to an expression. when smart-matches against topic and executes some code (followed by an implicit "next") if the match is successful.
given can be used without when and vice-versa.
given is useful for situations where you need to perform several operations on the result of an expression but don't want to name it, or in some cases, for when you want to emphasize an operation instead of the operand. For example, instead of 'say (some-long-complicated-expression.with-lots-of-calls-and-operators).perl', 'say .perl given the-expression'.
when can be used in given, but it can also be used in CATCH blocks (where $_ is set to the exception), or in for loops or other blocks where you are taking $_ as a parameter.