6

Now that the Perl devs have decided to sort-of deprecate given/when statements, is there a recommended replacement, beyond just going back to if/elsif/else?

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159

2 Answers2

7

if/elsif/else chains are the best option most of the time — except when something completely different is better than both if/elsif/else and given/when, which is actually reasonably often. Examples of "completely different" approaches are creating different types of objects to handle different scenarios, and letting method dispatch do your work for you, or finding an opportunity to make your code more data-driven. Both of those, if they're appropriate and you do them right, can greatly reduce the number of "switch statement" constructs in your code.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • 7
    In other words, the recomendation is to go back to the coding style used before the introduction of the 'given-when-default'! **I find that very frustrating,** – lexu Feb 21 '14 at 16:25
  • 1
    @lexu Even more frustrating is when you meet the nasty bugs from the experimental `given`/`when`. – FNia Feb 06 '22 at 10:46
0

Just as a supplement, I've found that a combination of 'for' and if/elsif/else is good if you have some given/when/default code that needs to be quickly updated. Just replace given with for and replace the when statements with a cascade of if & elsif, and replace default with else. This allows all your tests to continue using $_ implicitly, requiring less rewriting. (But be aware that other special smart match features will not work any more.)

This is just for rewriting code that already uses given/when, though. For writing new code, @hobbs has the right answer.

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159
  • Beware also that a `next` within `given` will behave differently from a `next` within `for`. – n.r. Oct 05 '16 at 13:10