<p>How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.</p>

[{'answer_id': 78301, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 2, 'selected': False, 'text': '<p>Use sub references, and closures. A good perlish example of this</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n'}, {'answer_id': 83715, 'author': 'tsee', 'author_id': 13164, 'author_profile': 'https://Stackoverflow.com/users/13164', 'pm_score': 4, 'selected': True, 'text': '<p>It really depends on what you mean by "clean implementation". As in any other language, you can use Perl\'s object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn\'t normally coded explicitly. Leon Timmermans\' example of</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n\n<p>demonstrates this quite elegantly.</p>\n\n<p>However, if you\'re looking for a "formal" implementation as you would do in C++, here\'s what it may look like using Perl+<a href="http://search.cpan.org/dist/Moose" rel="noreferrer">Moose</a>. This is just a translation of the C++ code from <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">Wikipedia -- Strategy pattern</a>, except I\'m using Moose\'s support for delegation.</p>\n\n<pre><code>package StrategyInterface;\nuse Moose::Role;\nrequires \'run\';\n\n\npackage Context;\nuse Moose;\nhas \'strategy\' =&gt; (\n  is      =&gt; \'rw\',\n  isa     =&gt; \'StrategyInterface\',\n  handles =&gt; [ \'run\' ],\n);\n\n\npackage SomeStrategy;\nuse Moose;\nwith \'StrategyInterface\';\nsub run { warn "applying SomeStrategy!\\n"; }\n\n\npackage AnotherStrategy;\nuse Moose;\nwith \'StrategyInterface\';\nsub run { warn "applying AnotherStrategy!\\n"; }\n\n\n###############\npackage main;\nmy $contextOne = Context-&gt;new(\n  strategy =&gt; SomeStrategy-&gt;new()\n);\n\nmy $contextTwo = Context-&gt;new(\n  strategy =&gt; AnotherStrategy-&gt;new()\n);\n\n$contextOne-&gt;run();\n$contextTwo-&gt;run();\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/78278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227001/']