<?xml version="1.0" encoding="utf-8"?>



<feed xmlns="http://www.w3.org/2005/Atom">
 
	<title>Atom Feed</title>
	<link href='http://mechanicalrevolution.com/feed.xml' rel="self" />
	<id>tag:mechanicalrevolution.com,2012-02-10:/list/feed</id>
	<updated>2012-02-10T12:57:11+00:00</updated>
	<author>
		<name>Your Name</name>
	</author>
 	
	
	<entry>
		<title>Annotations, Attributes, Traits - Part II</title>
		<link href='http://mechanicalrevolution.com/blog/annotations_attributes_traits_part_two.html' />
		<id>tag:mechanicalrevolution.com,2012-02-10:/annotations_attributes_traits_part_two</id>
		<updated>2012-02-10T12:48:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This post is a continuation of 
<a href="http://mechanicalrevolution.com/blog/annotations_attributes_traits.html">Annotations, Attributes, Traits</a> 
and explores the different options for applying metadata that are available to 
Perl, and what is needed to make these options available for third-party 
modules to use.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This post is a continuation of 
<a href="http://mechanicalrevolution.com/blog/annotations_attributes_traits.html">Annotations, Attributes, Traits</a> 
and explores the different options for applying metadata that are available to 
Perl, and what is needed to make these options available for third-party 
modules to use.</p>

<!-- BREAK -->

<h2 id="context">Context</h2>

<p>Let us start with a list of the contexts where we may have to set metadata:</p>

<ol>
<li>Variable declaration</li>
<li>Subroutine declaration</li>
<li>Package declaration</li>
<li>Moose attribute declaration</li>
</ol>

<p>The last item requires some explanation. The attribute syntax that Moose 
implemented has become pervasive in modern Perl modules, and is now used in 
many new libraries, whether related to Moose or not. Even though the new 
syntax proposed by Stevan implements attributes as variables, there are many 
other uses of attributes and it is safe to assume that they are here to stay 
for the time being (e.g. <code>HTML::FormHandler</code>, <code>DBIx::Class::Candy</code>, 
<code>Parse::FixedRecord</code>).</p>

<p>There is also Moose <em>type</em> declaration (<code>subtype</code>, <code>enum</code> and the like), 
which I have chosen to ignore in make the discussion more manageable. I do 
believe it will benefit from most of the proposals here.</p>

<p>Also, we will omit package declaration for the time being, as we will be 
talking about them later.</p>

<h2 id="anoteonattributecase">A note on attribute case</h2>

<p>All examples with perl attributes in this post use lowercase syntax. The 
attributes documentation currently advise against this practice, and perl 
will issue a warning when it encounters an non-core attribute starting with 
a lowercase letter. The main reason for this is to avoid conflicts with 
new core attributes that may be introduced in the future. My personal opinion 
is that:</p>

<ol>
<li><p>Lowercase names with underscores are way more perlish and look much better 
in most code, and if attributes are to gain wider usage I believe this syntax 
should definitely be permitted.</p></li>
<li><p>AFAIK, core perl has not added new attributes since 5.6 in which attributes 
were initially introduced.</p></li>
<li><p>Even if new attributes need to be added, at this stage it probably could 
(and should) be done in a module that requires explicit loading or via the 
<code>feature</code> pragma, so conflicts should not be an issue.</p></li>
</ol>

<h2 id="settingmetadata">Setting metadata</h2>

<p>We will now attempt to list <em>all</em> the different ways to set metadata in all 
the contexts listed above. Some of them we already discussed in the previous 
post.</p>

<h3 id="keywords">Keywords</h3>

<p>This is a way of setting metadata by changing the keyword for declaring the 
respective entity:</p>

<pre><code># variables
my $var;
our $var;
state $var;
has $var;

# subroutines
sub doit { ... }
method doit { ... }
action doit { ... }

# attributes
has name =&gt; ...
has_field name =&gt; ...
has_class name =&gt; ...
column name =&gt; ...
test name =&gt; ...
</code></pre>

<h3 id="keywordmodifiers">Keyword modifiers</h3>

<p>This method involves using a keyword before the main declaration keyword:</p>

<pre><code># variables
const my $var;

# subroutines
my sub doit { ... }
multi method doit { ... }

# attributes
class has 'name' ...
</code></pre>

<h3 id="type">Type</h3>

<p>The use of the type slot (between the declaration keyword and the entity name) 
is currently limited to variables:</p>

<pre><code>my Str $var;
</code></pre>

<p>It could possibly be implemented for subroutines too to indicate the return 
value, like Java does (if the subroutine ignores context) - but AFAIK Perl 6 
does not do it and there must be a good reason for that (e.g. because 
functions can return multiple values, which they can't in Java):</p>

<pre><code># method returning a string
method Str doit { ... }
</code></pre>

<p>In order to make types work with attributes, the attribute keyword must 
have a way to check if its first argument is a type name or the attribute name 
(which is probably not possible now):</p>

<pre><code>column Varchar 'name' ...
</code></pre>

<h3 id="assignment">Assignment</h3>

<p>The assignment operator as part of the declaration is only available to 
variables:</p>

<pre><code>my $var = 1;  # set value
has $var = 1; # set default value
</code></pre>

<p>It could theoretically be used for attributes with a similar meaning:</p>

<pre><code>column name = 1; # default column value
</code></pre>

<p>There could, of course, be other, more interesting uses. Just today I had a 
look at <code>Tie::Array::CSV</code>, prompted by an 
<a href="http://blogs.perl.org/users/joel_berger/2012/02/the-case-for-simplicity.html">entry on IronMan</a>:</p>

<pre><code>tie my @file, 'Tie::Array::CSV', 'filename';
</code></pre>

<p>With a clever use of the assignment operator this already nice syntax could 
be transformed into:</p>

<pre><code>my @file : csv = 'filename';
</code></pre>

<h3 id="signature">Signature</h3>

<p>The signature slot is only available to subroutines:</p>

<pre><code>sub doit (@args) { ... }
</code></pre>

<p>Its various potential uses were discussed in the 
<a href="http://mechanicalrevolution.com/blog/annotations_attributes_traits.html">previous post</a>.</p>

<h3 id="code">Code</h3>

<p>The code block slot is currently only available to subroutines:</p>

<pre><code>sub doit { ... }
</code></pre>

<p>It could theoretically be used with variables and attributes to assign e.g. a 
builder:</p>

<pre><code># declare a local variable whose value is the result of an expensive 
# calculation, but defer the calculation until the first time the value
# is requested
my $var :lazy { ... }; # shortcut for: my $var :lazy = sub { ... }
</code></pre>

<h3 id="attributes">Attributes</h3>

<p>Perl attributes are available to both variables and subroutines, and could be 
made available to Moose attributes via Devel::Declare:</p>

<pre><code># variables
my $var : ro = 1;
has $var : ro lazy build;

# subroutines
sub doit ($foo, %bar) : build_args check_args returns(Str) { ... }

# attributes
column name : data_type(VARCHAR) required;
</code></pre>

<p>Perhaps the most controversial point in these posts will be whether attributes 
should be used over simple lists as the primary syntax for metadata 
declaration. The attributes sytnax tends to be much more concise with common 
shorter declarations, especially when combined with some of the other patterns 
described above:</p>

<pre><code>has Str $name : ro required = 'John Smith'; 
</code></pre>

<p>vs. </p>

<p>has Str $name ( is => 'ro', required => 1 ) = 'John Smith';</p>

<p>When we add some complexity and choose not to use extra sytnax sugar, the 
scales tilt in favour of the list syntax, but I still prefer the attributes 
syntax as it adheres to the Perl moto of making easy things easy and hard 
things possible:</p>

<pre><code>has $names : ro required
    isa( 'HashRef' )
    default( sub {  first =&gt; 'John', family =&gt; 'Smith' } )
    traits( qw(Hash) )
    handles( get_names =&gt; 'elements', add_name =&gt; 'set' );
</code></pre>

<p>vs:</p>

<pre><code>has $names ( 
    is       =&gt; 'ro'
    required =&gt; 1,
    isa      =&gt; 'HashRef',
    default  =&gt; sub {  first =&gt; 'John', family =&gt; 'Smith' },
    traits   =&gt; [qw(Hash)],
    handles  =&gt; { get_names =&gt; 'elements', add_name =&gt; 'set' },
);
</code></pre>

<p>We can prettify the first declaration a little bit if we allow spaces between 
attribute names and the opening bracket:</p>

<pre><code>has $names : ro required
    isa     ( 'HashRef' )
    default ( sub {  first =&gt; 'John', family =&gt; 'Smith' } )
    traits  ( qw(Hash) )
    handles ( get_names =&gt; 'elements', add_name =&gt; 'set' );
</code></pre>

<p>Another point to keep in mind is that in order to provide a consistent syntax 
for metadata declaration, we will also need to implement the list syntax for 
subroutines too, which may not be an easy task, and will conflict with 
singatures:</p>

<pre><code>sub doit ($foo, %bar) ( build_args =&gt; 1, check_args =&gt; 1 ) { ... }
</code></pre>

<h3 id="metadataatadistance">Metadata at a distance</h3>

<p>The last way to set metadata is by code that is located in a different place 
from where the entity is declared. Many popular modules make use of this 
pattern:</p>

<pre><code># variables
readonly($var);

# subroutines
set_prototype('doit', '*$%');
memoize('doit');
</code></pre>

<p>In many cases, there exists a more concise syntax to achieve the same goal at 
the time of declaration:</p>

<pre><code>const my $var = ...;
sub doit : prototype('*$%') { ... }
sub doit : memoize { ... }
</code></pre>

<p>Sometimes, however, there isn't. One specific case is subroutines with 
multiple bodies. Consider a Catalyst action that implements a form via 
Catalyst::Controller::HTML::FormFu:</p>

<pre><code>sub edit :Local :Args(1) :Form { ... }
sub edit_FORM_ERROR { ... }
sub edit_SUBMITTED_AND_VALID { ... }
</code></pre>

<p>The underlying metadata syntax is:</p>

<pre><code>subroutine( 
    name =&gt; edit, 
    body =&gt; \&amp;edit, 
    on_form_error =&gt; \&amp;edit_FORM_ERROR,
    on_form_submitted_and_valid =&gt; \&amp;edit_SUBMITTED_AND_VALID,
    ...
);
</code></pre>

<p>The above could be more elegantly expressed as:</p>

<pre><code>action edit : ... { ... }
form_error edit { ... }
form_submitted_and_valid edit { ... }
</code></pre>

<p>Or even:</p>

<pre><code>action edit : ... { ... }
form edit : error  { ... }
form edit : submitted_and_valid { ... }
</code></pre>

<p>In a similar vein, it is open to debate whether method modifiers implement 
the 'keyword' pattern (i.e. they declare a completely new code entity) or the 
'metadata at a distance' pattern (i.e. they modify an existing code entity).</p>

<h2 id="todo">TODO</h2>

<p>This is all nice and pretty, but unfortunately some of the changes required to 
make the above examples work may involve meddling with the perl core. Here is 
what I believe can and cannot be implemented via external modules today:</p>

<h3 id="genericmechanismtoallowapplicationofmetadatatoentities">Generic mechanism to allow application of metadata to entities</h3>

<p>In the first place there needs to be a mechanism where code can hook into the 
entity creation event in order to do its magic. For example, let's say I want 
to have a testing module that can automatically create custom fixtures based 
on the sub signature, and make them available as lexical variables.</p>

<pre><code>sub test_cart (MyApp::Fixture::ShoppingCart::TwoApples $cart) { 
    ... # use the $cart here
}
</code></pre>

<p>There is currently no way for my module to hook into the subroutine creation 
event (the event caputred by <code>Sub::Mutate::when_sub_bodied</code>) - or at least no 
way that is obvious to a non-XS-savvy developer, and request random code to be 
executed at that point. The <code>signatures</code> pragma does this, but in a way that 
does not seeem reusable by other modules.</p>

<p>Another problem is that it is currently difficult to introspect all the 
differnt types of metadata applied durint the declaration of a given entity. 
In a fancy variable declaration:</p>

<pre><code>my Str $var : foo bar;
</code></pre>

<p>the <code>foo</code> attribute has no way to tell that the <code>bar</code> attribute has been 
specified too - and vice versa, and neither knows that there is a type 
restriction as well.</p>

<p>I think Moose has solved this problem quite elegantly, and has a solid 
interface for extensions to inspect and modifty attribute properties, set 
defaults, and add new properties. This approach could be extended to handle 
different kinds of entities:</p>

<pre><code># this is how modules like Attribute::Handlers and Attribute::Lexical
# currently work
sub MyAttribute ($package, $symbol, $referent, $attr, $data) { ... }

# instead we could have a function 'with meta', i.e. it gets passed 
# a method object that contains all the information above, plus 
# information about the other attributes, the prototype, etc.
sub MyAttribute ($metamethod) {
    if $metamethod-&gt;has_attribute('OtherAttribute') {
        do_this();
    } else {
        do_that();
    }
}
</code></pre>

<p>All of the proposals below depend on such a protocol being available.</p>

<h3 id="keywords">Keywords</h3>

<p>Perl already has a very good system for introducing new keywords, both for 
variable and subroutine declaration, with Devel::Declare. Changing the way 
built-in functions work is more difficult, but apparently not impossible 
(see the <code>signatures</code> pragma for example).</p>

<h3 id="keywordmodifiers">Keyword modifiers</h3>

<p>Any subroutine can act as a keyword mofifier for variables. Ditto for Moose 
attributes (e.g. if <code>has</code> in non-void context returns the meta object rather 
than installing it), although I could not find any modules actually doing 
that.</p>

<p>Keyword modifiers for plain perl subs are not currently possible, although I 
have a suspicion that this should be doable with Devel::Declare.</p>

<h3 id="type">Type</h3>

<p><code>Lexical::Types</code> makes the type slot usable to an extent. While some jumping 
around hoops will be required, it is not impossible to come up with a solution 
that allows using <code>MooseX::Types</code>-style type names on variable 
declaration. Anything more complicated will unfortunately need changes to the 
Perl parser. </p>

<p>Another caveat is that types are currently only available to scalar variables. 
The docs say:</p>

<pre><code>Currently, only scalar variables can be declared with a specific class 
qualifier in a "my", "our" or "state" declaration. The semantics may be 
extended for other types of variables in future.
</code></pre>

<p>So core changes will also be required in order to do something like:</p>

<pre><code>my Str @array_of_strings;
</code></pre>

<h3 id="assignment">Assignment</h3>

<p>Capturing assignment is relatively straighforward with <code>tie</code>, and I believe 
also possible with <code>Variable::Magic</code>. Assignment support for Moose-style
attributes could be implemented with Devel::Declare.</p>

<h3 id="signature">Signature</h3>

<p>The prototype slot could be set to anything with <code>warnings::illegalproto</code> 
disabled, and then introspected with the <code>prototype</code> function. There are
two caveats, however: first, the prototype cannot span more than one line; 
and second, <code>prototype()</code> will return the prototype as a string with all 
whitespace stripped. Thus it is currently not possible to have a signature 
implementation that can use more than one line for longer declarations, or 
for which whitespace is significant.</p>

<h3 id="attributes">Attributes</h3>

<p>Attributes are available to both subroutines and variables, and can be made 
available to Moose-style attributes via Devel::Declare.</p>

<p>There are two limitations in the current attribute implementation that I find 
particularly frustrating:</p>

<p>First, the attribute data (whatever is in the brackets after the attribute 
name) cannot access the current context. This means that you cannot refer to <br />
a variable or subroutine defined in the scope where the attribute is used:</p>

<pre><code>my @traits = qw(Hash MergeHashRef);
my %hash : traits(\@traits) ... # Nope!
</code></pre>

<p>Ideally the code taht manages attribute application should be able to capture 
the environment at the point where the attribute is used via a mechanism 
similar to <code>Parse::Perl::current_environment()</code>, and then make it available 
to the attribute handler:</p>

<pre><code>sub MyAttributeHandler ($data, $env, ... ) {
    @data = Parse::Perl::parse_perl($env, $data);
    ...
}
</code></pre>

<p>Second, the Perl parser currently does not allow spaces between the attribute 
name and the opening bracket after it. Doing this would allow for much nicer 
looking attribute specifications:</p>

<pre><code>has $ssn : rw
  clearer   (clear_ssn)
  predicate (has_ssn);
</code></pre>

<h2 id="conclusion">Conclusion</h2>

<p>Despite their reputation, attributes seem a reasonable way to implement a 
consistent mechanism for metadata application in Perl. Combined with other 
syntax features, they meet all three criteria - extensible, consistent and 
concise.</p>
</div></content>
	</entry>
 	
	<entry>
		<title>Annotations, Attributes, Traits</title>
		<link href='http://mechanicalrevolution.com/blog/annotations_attributes_traits.html' />
		<id>tag:mechanicalrevolution.com,2012-02-07:/annotations_attributes_traits</id>
		<updated>2012-02-07T18:30:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>At last year's LPW, Stevan Little demonstrated a draft implementation of a new class system for Perl 5 (<a href="http://www.presentingperl.org/lpw2011/a-brave-new-perl-world/">talk video can be found here</a>). Here is how the proposed syntax works: </p>

<pre><code>class Point {
    has $x ( is =&gt; 'rw' ) = 0;
    has $y ( is =&gt; 'rw' ) = 0;

    method clear {
        ($x, $y) = (0, 0);
    }
}
</code></pre>

<p>One of the questions that came up during the discussion afterwards was what is the best syntax for declaring the rich sets of additional metadata associated with class members and methods. This post is my take on the options that we have.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>At last year's LPW, Stevan Little demonstrated a draft implementation of a new class system for Perl 5 (<a href="http://www.presentingperl.org/lpw2011/a-brave-new-perl-world/">talk video can be found here</a>). Here is how the proposed syntax works: </p>

<pre><code>class Point {
    has $x ( is =&gt; 'rw' ) = 0;
    has $y ( is =&gt; 'rw' ) = 0;

    method clear {
        ($x, $y) = (0, 0);
    }
}
</code></pre>

<p>One of the questions that came up during the discussion afterwards was what is the best syntax for declaring the rich sets of additional metadata associated with class members and methods. This post is my take on the options that we have.</p>

<!-- BREAK -->

<h2 id="whatstheproblem">What's the problem</h2>

<p>I believe Perl 5 needs to have a way to apply metadata annotations to different entities (i.e. subroutines, variables, packages, types), which meets the following criteria:</p>

<h3 id="extensible">Extensible</h3>

<p>Most programming langauges provide a syntax (see below) that allows developers to apply arbitrary metadata to entities. I would like to see Perl go beyond that and make <em>all</em> the different syntaxes for declaring various types of metadata (keywords, prototypes, types) available for developers to use.</p>

<h3 id="consistent">Consistent</h3>

<p>I think this is the biggest problem with the current state of metadata syntax in Perl. The sugar syntax for Moose attributes is nice, but it cannot currently be used for other types of entities - e.g. subroutines or lexical variables. The <code>method</code> keyword provided by Devel::Declare-based modules behaves almost like the built-in <code>sub</code> keyword, but not quite. Looking at the three most popular implementations of the <code>method</code> keyword - <code>Method::Signatures</code>, <code>MooseX::Method::Signatures</code>, and <code>Method::Signatures::Simple</code>:</p>

<pre><code>method NAME;               # a "forward" declaration - broken in all three
method NAME : ATTRS BLOCK  # with attributes - only works in Method::Signatures
$methodref = method BLOCK; # anonymous method - broken in MooseX::Method::Signatures
</code></pre>

<p>Also, if you use signatures with a <code>method</code> keyword, you cannot use the same signatures with the <code>sub</code> keyword, for no other reason but limitations of the Perl parser. Similarly, some modules allow you to do funky things such as <code>multi method ...</code>, but not <code>multi sub ...</code>. Until Perl has a way to resolve these inconsistencies, the new syntax will look experimental to many people and adoption levels will remain marginal.</p>

<h3 id="concise">Concise</h3>

<p>We want syntax that is kind to both the eyes and the fingers, and that we can be proud of when standing next to other programming languages.</p>

<h2 id="howdifferentlanguagesdoit">How different languages do it</h2>

<p>Different languages have at different stages in their evolution reached a point where they needed a way to declare arbitrary additional information about a given entity.</p>

<h3 id="perl5attributes">Perl 5 attributes</h3>

<p>Perl 5 added attributes in version 5.6. Attributes can be attached to a vairable or a subroutine. Some examples of how attributes are used:</p>

<pre><code>my %hash : Tie(Tied::Class) = ...; # Tie::Attributes 
sub calculate : Memoized { ... } # Attributes::Memoize
sub edit : Chained(/) PathPart(edit) Args(0) { ... } # Catalyst
</code></pre>

<p>Due to some limitations in their implemenation, attributes do not enjoy a stellar reputation in the Perl world:</p>

<ul>
<li>Attributes are normally declared at compile-time and cannot be manipulated during runtime.</li>
<li>Attributes are difficult to introspect.</li>
<li>Declaring attributes is tricky and may involve polluting your symbol table.</li>
<li>Attributes provided by different modules do not play well together.</li>
<li>The attribute argument cannot access symbols from its context (i.e. <code>my $lazy_var :Builder(\&amp;_builder_sub)</code> does not work).</li>
</ul>

<h3 id="perl6traits">Perl 6 traits</h3>

<p>Perl 6 comes with a powerful annotation syntax out of the box. Traits can be applied to classes, functions and variables:</p>

<pre><code>constant $pi is Approximated = 3;
my $key is Persistent(:file&lt;.key&gt;);
sub fib is cached {...}
</code></pre>

<h3 id="javaannotations">Java annotations</h3>

<p>Metadata annotations were introduced in J2SE 5.0. </p>

<pre><code>@Test
public static void edit { ... }
</code></pre>

<h3 id="cattributes">C# attributes</h3>

<p>C# attributes, based on Java's annotations, were introduced in .NET 1.1, :</p>

<pre><code>[Test]
public static void edit { ... }
</code></pre>

<p>Attributes can be added to packages, types, methods, parameters, members and variables.</p>

<h3 id="pythondecorators">Python decorators</h3>

<p>Python calls them decorators and borrows Java's syntax. Python decorators can be used to annotate a class, function or method:</p>

<pre><code>@Test
def edit
    ...
</code></pre>

<p>Decorators were first introduced in Python 2.3. A fascinating overview of the different proposals for decorator syntax can found in <a href="http://www.python.org/dev/peps/pep-0318/">this PEP</a>.  </p>

<h3 id="otherlanguages">Other languages</h3>

<p>Unfortunately this is where my knowledge ends, feel free to add more examples in the comments ...</p>

<h2 id="butwhatareannotationsanyway">But what are annotations anyway?</h2>

<p>Let us backtrack for a moment and consider what a metadata annotation is. Moose's powerful attributes (not to be confused with Perl's built-in attributes) are a very good starting example:</p>

<pre><code>has 'name', is =&gt; 'ro', isa =&gt; 'Str', required =&gt; 1;
</code></pre>

<p>With other types of constructs, identifying annotations is less clear:</p>

<pre><code># annotate function 'bar' as exportable - classic implementation
use base 'Exporter';
our @EXPORT = qw(bar)';
sub bar { ... }

# attributes-based implementation
use Perl6::Export::Attr;
sub bar :Export(:DEFAULT) { ... }

# and a Moose-style implemetation might look like this:
function 'bar', export =&gt; 1, body =&gt; sub { ... };

# a few possible syntaxes to annotate something as read-only:
readonly my $var            # call a function on declaration
my $var :readonly           # use attributes
use readonly var =&gt; ...     # a pragma
readonly qw('$var')         # call a funcion on symbol name 
has 'var', is =&gt; 'readonly' # Moose-style properties
</code></pre>

<p>So, while there may be different ways to associate metadata with an object, ultimately it can always be expressed as a list of properties applied to that entity, e.g.:</p>

<pre><code># pseudocode
function ( name =&gt; 'bar', export =&gt; 1, body =&gt; sub { ... } );
variable ( name =&gt; 'var', type = 'scalar', read_only =&gt; 1, value = ... );
</code></pre>

<p>This is basically how Moose's meta protol stores information internally. You could use Moose sugar keywords to create objects, or raw <code>Class::MOP</code> meethods, or you could create them using Perl's built-in syntax, but it all ends up looking the same underneath. Hence my three rules of metadata:</p>

<ol>
<li>Everything is metadata</li>
<li>There is more than one way to apply metadata</li>
<li>But all metadata is the same on the inside</li>
</ol>

<p>If you start thinking in metadata, you realize that most syntax is just sugar for metadata application, and you start appreciating that powerful and elegant metadata manipulation tools in a programming langauge are the most important requirement for writing powerful and elegant software. That is why I am very keen for Perl to be great with metadata. I think it is already 90 percent there, but there is still some work to be done. My experiments in creating an interface for MooseX::Params provide a good illustration of what is in my opinion one of the better approaches.</p>

<h2 id="theevolutionofmoosex::params">The evolution of MooseX::Params</h2>

<p>Moose's attribute syntax is quite powerful and suffers from none of the limitations of Perl's built-in attributes. This is why the original implementation of <a href="http://search.cpan.org/perldoc?MooseX::Params">MooseX::Params</a> used that to define methods on steroids:</p>

<pre><code>method 'foo', args =&gt; [ ... ], build_args =&gt; 1, returns =&gt; 'Str', body =&gt; sub { ... };
</code></pre>

<p>But the problem with this syntax is that it becomes very verbose very quickly. In a programming language that counts the number of characters in commonly used built-in keywords, the above statement contains a few arrows too many (and commans, and quotes ...). A number of modules exist on CPAN to address Moose's verbosity (<a href="http://search.cpan.org/perldoc?MooseX::Has::Options">MooseX::Has::Options</a>, <a href="http://search.cpan.org/perldoc?MooseX::Has::Sugar">MooseX::Has::Sugar</a>), but eventually MooseX::Params chose to start using function attributes:</p>

<pre><code>sub foo : Args(bar, baz) BuildArgs Returns(Str) { ... }
</code></pre>

<p>Even then people complained that having to type column-Args for every simple subroutine is quite a nuisance. So the <a href="http://github.com/pshangov/moosex-params/tree/sigs_form_proto">latest version on git</a> attempts (semi-successfully) to hijack the prototype slot for the signature:</p>

<pre><code>sub foo (bar, baz) : BuildArgs Returns(Str) { ... }
</code></pre>

<p>What we have done is, we have used the language's built-in syntax to fill a metadata slot. There is nothing particularly innovative about this - in an ordinary program, most metadata slots are filled in not using the extended metadata syntax (attributes, traits, decorators or whatever) but by built-in language syntax. This Java method declaration:</p>

<pre><code>@Test
public static string foo ( string bar, int baz ) { ... }
</code></pre>

<p>is just a concise way to write this:</p>

<pre><code>method ( 
    name       =&gt; 'foo', 
    scope      =&gt; 'public', 
    static     =&gt; 1,
    returns    =&gt; 'string',
    parameters =&gt; [ bar =&gt; ..., baz =&gt; ... ],
    test       =&gt; 1,
    body       =&gt; sub { ... },
);
</code></pre>

<p>All programming languages we desribed above provide special syntax slots for commonly used types of built-in metadata, and a catch-all syntax for any additional medatata. What makes Perl intersting is that at least some of the special built-in metadata slots are actually available for third party modules to use. </p>

<h2 id="hookablesyntax">Hookable syntax</h2>

<p>Let us look in more detail at those special syntax slots. The first example, which we already mentioned, is the prototype slot. Core Perl uses it for prototype declaration. <code>MooseX::Params</code> and the <code>signatures</code> pragma use it for signature declaration. <code>Web::Simple</code> uses it for route specification:</p>

<pre><code>sub foo (*&amp;)         # prototype
sub foo ($bar, $baz) # signatures pragma signature
sub foo (bar, baz)   # MooseX::Params signature
sub foo (/foo)       # Web::Simple route
</code></pre>

<p>A less obvious example of how built-in syntax can be used to modify metadata information is the assignment operator. By using tie or Variable::Magic, for example, we can theoretically hijack the assignment process and make it produce various side-effects, including changing the metadata information for the affected variable. Albeit by different means, the proposed new class syntax uses the assignment operator to set the default value of the class member, which is different from its actual value:</p>

<pre><code>has $foo = 'bar'; # set 'foo' to 'bar' unless a different 
                  # value is passed to the constructor
</code></pre>

<p>Perl has another convenient metdata slot which due to its limitations has remained largely unused:</p>

<pre><code>my Foo $bar = Foo-&gt;new;
</code></pre>

<p>The type slot allows you to specify that the given variable must contan an object that is an instance of the specified class. Unfortunately, this slot is tricky for third-party modules to make good use of. Currently the <code>types</code> pragma uses it to provide compile-time hints to the optimizer, <code>MooseX::Lexical::Types</code> provides limited support for Moose type validation, and <code>Lexical::Types</code> uses it to automatically bless lexicals into objects.</p>

<pre><code>my int $foo; # optimization with the types pragma
my Int $foo; # validation with MooseX::Lexical::Types
my Int $foo; # automatically blessed with Lexical::Types
</code></pre>

<p>It is possible that future perls will make it even easier for modules to access the information from this slot and put is to better use (another possible application that comes to mind is datatype declarations for database columns in an ORM).</p>

<h2 id="asyntaxforperlclasses">A syntax for Perl classes</h2>

<p>And finally we are back to where we started from. I believe Perl's existing syntax is powerful enough to provide succint and extensible metadata declarations. Given you run-of-the-mill Moose attribute:</p>

<pre><code>has 'foo', is =&gt; 'ro', isa =&gt; 'Str', lazy =&gt; 1, default =&gt; 'bar';
</code></pre>

<p>I would love to be able to write the above declaration as:</p>

<pre><code>has Str $foo : ro lazy = 'bar';
</code></pre>

<p>And have methods that do:</p>

<pre><code>method foo (Str $bar, Int $baz) : build_args returns(Str) { ... } 
</code></pre>

<p>It is perlish, nice and clean.</p>

<p>Stay tuned for the next post, where we will delve deeper into more complicated metadata, functions with mutiple bodies, and challenges to metadata declaration in general.</p>
</div></content>
	</entry>
 	
	<entry>
		<title>Catalyst::Model::FormFu</title>
		<link href='http://mechanicalrevolution.com/blog/catalyst_model_formfu.html' />
		<id>tag:mechanicalrevolution.com,2011-07-06:/catalyst_model_formfu</id>
		<updated>2011-07-06T21:03:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://search.cpan.org/dist/Catalyst-Model-FormFu/">Catalyst::Model::FormFu</a> has just hit CPAN. It is an experimental alternative interface to <a href="http://search.cpan.org/dist/HTML-FormFu/">HTML::FormFu</a> for Catalyst and its main puprpose is to provide improved performance over the existing <a href="http://search.cpan.org/dist/Catalyst-Controller-HTML-FormFu/">Catalyst::Controller::HTML::FormFu</a>. It parses the form configuration files and loads form objects during application startup, and then returns clones of these objects inside your actions. It is hard to evaluate precisely the performance boost that this provides (disk access speed will vary, and there is always the Catalyst overhead), but my crude benchmarks indicate that you can expect a form object to be loaded at least twice as fast when using <code>Catalyst::Model::FormFu</code>.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://search.cpan.org/dist/Catalyst-Model-FormFu/">Catalyst::Model::FormFu</a> has just hit CPAN. It is an experimental alternative interface to <a href="http://search.cpan.org/dist/HTML-FormFu/">HTML::FormFu</a> for Catalyst and its main puprpose is to provide improved performance over the existing <a href="http://search.cpan.org/dist/Catalyst-Controller-HTML-FormFu/">Catalyst::Controller::HTML::FormFu</a>. It parses the form configuration files and loads form objects during application startup, and then returns clones of these objects inside your actions. It is hard to evaluate precisely the performance boost that this provides (disk access speed will vary, and there is always the Catalyst overhead), but my crude benchmarks indicate that you can expect a form object to be loaded at least twice as fast when using <code>Catalyst::Model::FormFu</code>.</p>

<!-- BREAK -->

<p>Additionally, since <code>Catalyst::Model::FormFu</code> does not inherit from <code>Catalyst::Controller</code>, it can be used with <code>Catalyst::Controller::ActionRole</code> - a feature many users have requested. Also, you can easily work with more than one form object inside a single action, which was there was no straightforward way to do before.</p>

<p>The configuration options are very simialar to those of <code>Catalyst::Controller::HTML::FormFu</code>, except that you must also specify a hash of forms whose values are the configuration files corresponding to each form, e.g.:</p>

<pre><code>&lt;Model::FormFu&gt;
    &lt;constructor&gt;
        config_file_path "myapp/root/forms"
    &lt;/constructor&gt;
    &lt;model_stash&gt;
        schema Books
    &lt;/model_stash&gt;
    &lt;forms&gt;
        book book.conf
        author author.conf
    &lt;/forms&gt;
&lt;/Model::FormFu&gt;
</code></pre>

<p>You can then access form objects like this:</p>

<pre><code>sub edit :Local
{
    my ($self, $c, @args) = @_;
    my $book = $c-&gt;model('FormFu')-&gt;form('book');
    if ($book-&gt;submitted_and_valid)
    ...
}
</code></pre>
</div></content>
	</entry>
 	
	<entry>
		<title>Perl, Names and World Domination</title>
		<link href='http://mechanicalrevolution.com/blog/perl_names_and_world_domination.html' />
		<id>tag:mechanicalrevolution.com,2011-06-29:/perl_names_and_world_domination</id>
		<updated>2011-06-29T22:27:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Making a clean break from what draws you back is important. Whither can we go if "Perl 5" has lost its coolness factor, and "Perl 6" is already taken? But the path to world domination and greater numbers of "ninja perl programmers" and "perl rockstars" need not not necessarily go through the name of Perl itself. It did not for Ruby - it was Rails that did it. Here is my recipe:</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Making a clean break from what draws you back is important. Whither can we go if "Perl 5" has lost its coolness factor, and "Perl 6" is already taken? But the path to world domination and greater numbers of "ninja perl programmers" and "perl rockstars" need not not necessarily go through the name of Perl itself. It did not for Ruby - it was Rails that did it. Here is my recipe:</p>

<!-- BREAK -->

<ul>
<li><strong>Step 1:</strong> Bundle essential modern Perl libraries in a single Task distribution - akin to Task::Kensho, but sans the domain specific stuff for xml, web, and the like. Think Moose, perlbrew, local::lib, CPAN::Mini, Perl::Critic, Perl::Tidy, Dist::Zilla, Regexp::Grammars, plus a selection of useful modules like Path::Class, Try::Tiny, File::Find::Rule, Perl6::Caller, etc. Spice up with some goodies for everyday development such as Data::Printer, Devel::REPL and Carp::Always.</li>
<li><strong>Step 2:</strong> Give it a fancy name - Perl 5 Extended Library, Perl 5 Power Libs, whatever. A poll for ideas should certainly produce some appealing suggestions.</li>
<li><strong>Step 3:</strong> Make it available everywhere. Include it in the standard Strawberry Perl distribution. Make packages for major unixes (and name them properly, e.g. perl-extended-lib rather than libtask-extendedlib-perl). Make sure it installs flawlessly on all platforms.</li>
<li><strong>Step 4:</strong> Market the hell out of it. Create a subdomain under perl.org (e.g. exlib.perl.org), make the docs for the included libraries available under a special section in perldoc.org, create a cpanel plugin to install it to shared hosts, create a logo that shared hosts can use to signify that they provide these modules to their perl users. Own the SEO for that name. Talk to publishers to write books about it ("Mastering the Extended Perl Library", "Extended Perl Library in a Nutshell").</li>
<li><strong>Step 5:</strong> Rule your newfound minions</li>
</ul>

<p>The point is to transform a disparate set of essential modern Perl modules and practices into something concrete and marketable. This will make buzz about Perl more effective, trolls online will be easier to silence, newbees will know where to go after the camel and the alpaca, people curious about perl will know where to go and have a look. Even more importantly, IT managers will have a clear path path for training their developers, and clear expectations from potential hires - standards and predictability rule in the enterprise world. A flagship project like that may just prove to be what it takes to drive Perl adoption forward.</p>
</div></content>
	</entry>
 	
	<entry>
		<title>My DarkPAN Setup</title>
		<link href='http://mechanicalrevolution.com/blog/my_darkpan_setup.html' />
		<id>tag:mechanicalrevolution.com,2011-06-19:/my_darkpan_setup</id>
		<updated>2011-06-19T23:21:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>chromatic wrote about <a href="http://www.modernperlbooks.com/mt/2011/06/my-passthrough-darkpan.html">setting up a private CPAN to store your code</a>. I am a big fan of this appropach, and I think that managing code as distributions, rather than as a bunch of stuff in a version control repo (which is the predominant practice in most shops), is the one and only way to go. Here is how we have set things up at $work:</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>chromatic wrote about <a href="http://www.modernperlbooks.com/mt/2011/06/my-passthrough-darkpan.html">setting up a private CPAN to store your code</a>. I am a big fan of this appropach, and I think that managing code as distributions, rather than as a bunch of stuff in a version control repo (which is the predominant practice in most shops), is the one and only way to go. Here is how we have set things up at $work:</p>

<!-- BREAK -->

<ol>
<li>A CPAN::Mini mirror is set up on one of the company's machines. An apache web server makes it accessible at cpan.company.com via password-protected http (we use mod_auth_krb to authenticate against our Kerberos-based SSO solution). Now all clients can setup their main mirror with <code>o conf urllist</code>, as <code>cpan.company.com</code>, and their username and password with <code>o conf username</code> and <code>o conf password</code> respectively.</li>
<li>We make the local mirror injectable with <a href="http://search.cpan.org/dist/CPAN-Mini-Inject/">CPAN::Mini::Inject</a>, and additionaly configure <a href="http://search.cpan.org/dist/CPAN-Mini-Inject-Server/">CPAN::Mini::Inject::Server</a> so that we can inject from remote machines. <code>CPAN::Mini::Inject::Server</code> is also served by a password-protected apache at e.g. <code>cpaninject.company.com</code>.</li>
<li>Developers who need to push distributions into the mirror have <a href="http://search.cpan.org/dist/CPAN-Mini-Inject-Remote/">CPAN::Mini::Inject::Remote</a> and <a href="http://search.cpan.org/dist/Dist-Zilla-Plugin-Inject/">Dist::Zilla::Plugin::Inject</a> installed. All distributions are managed by <code>Dist::Zilla</code>, so they only need to do <code>dzil release</code> in order to get their stuff into the mirror and make it available to everyone else. We use a company-wide <code>Dist::Zilla</code> plugin bundle which contains all server settings for <code>Dist::Zilla::Plugin::Inject</code>, so it is zero configuration for them - they just need to install it and are ready to upload.</li>
<li>I am still working on choosing an appropriate solution to serve the docs for our Perl code (<code>perldoc.company.com</code>). There is a lot of choice out there, I have yet to see what will work best for us...</li>
</ol>

<p>What do we gain from working this way?</p>

<ul>
<li>Code is reusable across applications. We don't have one monolithic product, rather we have a number of smaller program which reuse a lot of functionality. Structuring code in distributions makes this a breeze.</li>
<li>Management of dependencies when deploying is extremely easy.</li>
<li>And last but not least, we get to work with the awsome <code>Dist::Zilla</code> :-)</li>
</ul>

<p>This is, however, still not a widesperad approach, and we have encountered many issues while implementing it:</p>

<ul>
<li>There are a lot of ways to solve this problem. Other than the tools outlined above, there are <a href="http://search.cpan.org/dist/CPAN-Site/">CPAN::Site</a>, <a href="http://search.cpan.org/perldoc?CPANPLUS::Shell::Default::Plugins::CustomSource">CPANPLUS::Shell::Default::Plugins::CustomSource</a>, <a href="http://search.cpan.org/dist/MyCPAN-App-DPAN/">MyCPAN::App::DPAN</a>, and now <a href="https://github.com/chromatic/CPAN-Dark">CPAN::Dark</a>, and probably others I don't know about. And then you could go with par, ppm, deb, rpm, git submodules, and more. Each of these approaches has its pros and cons, and one has to go through a lot of trial and error in order to fiture out what works for them. It would be good if there was one solution that does most of what people want and is easy to setup and use (like what <code>Moose</code> does to OO and <code>Dist::Zilla</code> does to distribution building). And then there are even  more solutions if you want to server POD locally or put some kind of web interface for your CPAN. What I would love to be able to just grab a distro with the code for current <a href="http://www.metacpan.org/">metacpan.org</a> interface and have it seamlessly integrate with my mirror, so that I can search it, browse it, read docs, etc.</li>
<li>I could not find much information on what author names I could use when deploying to a private CPAN, or what namespaces are safe to use for local distributions. Whatever exists as standards is spread out in different places, hard to find, and often discouraging. For example, what if I want to use other author names instead of the reserved <code>LOCAL</code>?</li>
<li>Most code with an architecture that uses somthing like <code>Module::Pluggable</code> to load stuff (think <code>DBIx::Class</code> resultsources and <code>Catalyst</code> components) is very painful to deploy as an installable distribution.  If a module is removed from a distribution (e.g. you have deleted a table and its associated result class), an upgrde via CPAN will not prevent the old module from still being picked up. This is a long-standing issue for CPAN and I am not sure how it can be resolved. Currently we deal with this by using <code>load_classes</code> with explicit resultsource names in our <code>DBIx::Class</code> schemas, and we never install <code>Catalyst</code> distributions (<code>Catalyst</code> is not installation-friendly to begin withm, which is kind of OK since <code>Catalyst</code> apps are never used as dependencies themselves).</li>
<li>Using a passthrough mirror (the approach that <code>CPAN::Dark</code> relies on) works with <code>cpanminus</code>, but I cannot see a way to configure it via the standard CPAN or CPANPLUS shell. Similarly, CPANPLUS's custom sources work only with the <code>cpanp</code> shell. It would be great if there is a standard for querying more than one location for a module and all clients supported it. We do not really need to keep a full CPAN mirror on our servers, we only need a place to keep our private code.</li>
<li>And last but not least, there is little support for using password-protected mirrors. The standard shell supports only http authentication, and stores the username and password in plain text. If private CPANs are to gain wider acceptance in corporate environmens, support for more authentication protocols and more secure ways to store credentials would probably be essential.</li>
</ul>

<p>In an ideal world, distributions would be the default way to manage perl code even for the newbee programmer. It should be simple and expected to setup your own passtthrough mirror on a shared hosting for the code you write, and the standard way to deploy stuff should be through <code>cpan</code> and <code>local::lib</code>, even for the smallest of applications.</p>
</div></content>
	</entry>
 	
	<entry>
		<title>MooseX::Params Usage Examples</title>
		<link href='http://mechanicalrevolution.com/blog/moosex_params_usage_examples.html' />
		<id>tag:mechanicalrevolution.com,2011-06-14:/moosex_params_usage_examples</id>
		<updated>2011-06-14T00:04:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><code>MooseX::Params</code> (my experiment in parameter processing) has undergone some changes and only the the attributes-based interface has been left now. Here are some examples from the synopsis of how it works. Most of them have been adapted from the <a href="http://search.cpan.org/perldoc?Moose::Manual">Moose manual</a> and the subroutines chapter of <a href="http://szabgab.com/talks/perl6/">Gabor Szabo's Perl 6 tutorial</a>.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><code>MooseX::Params</code> (my experiment in parameter processing) has undergone some changes and only the the attributes-based interface has been left now. Here are some examples from the synopsis of how it works. Most of them have been adapted from the <a href="http://search.cpan.org/perldoc?Moose::Manual">Moose manual</a> and the subroutines chapter of <a href="http://szabgab.com/talks/perl6/">Gabor Szabo's Perl 6 tutorial</a>.</p>

<!-- BREAK -->

<p>In brief, parameters are declared via the <code>Args</code> attribute, and made available in the <code>%_</code> hash. You can use Moose types for validation, and an ampersand before a type constraint enables coercion.</p>

<pre><code>sub add :Args(Int first, Int second) {
  return $_{first} + $_{second};
}

say add(2, 3); # 5
say add(2);    # error

subtype 'HexNum', as 'Str', where { /[a-f0-9]/i };
coerce 'Int', from 'HexNum', via { hex $_ };

sub add2 :Args(&amp;Int first, &amp;Int second) {
  return $_{first} + $_{second};
}

say add2('A', 'B'); # 21

# you can mix named and positional
sub add3 :Args(a, :b) {
  return $_{a} + $_{b} * 2;
}

# say add3( 3, b =&gt; 2 ); # 7
# say add3(4, 9);        # error
# say add3(2);           # error
# say add3(2, 3, 4);     # error
</code></pre>

<p>Slurpy arguments consume the remainder of <code>@_</code>.</p>

<pre><code>sub sum :Args(ArrayRef *values) {
  my $sum = 0;
  my @values = @{$_{values}};

  foreach my $value (@values) {
    $sum += $value;
  }
  return $sum;
}

say sum(2, 3, 4, 5); # 14
</code></pre>

<p>In this subroutine the parameter 'all' is optional. If not present it searches the text within a file and returns 1 if found, 0 if not; if present it searches the text and returns the number of lines in which the text is found.</p>

<pre><code>sub search :Args(text, fh, all?) {
  my $cnt = 0;

  while (my $line = $_{fh}-&gt;getline) {
    if ( index($line, $_{text}) &gt; -1 ) {
      return 1 if not $_{all};
      $cnt++;
    }
  }

  return $cnt;
}
</code></pre>

<p>Paramerers can have simple defaults, or full-blown lazy parameter builders:</p>

<pre><code>sub shop :Args(:size = 'medium', :color = 'white') { ... }

sub shop2 :Args(
  :size   = _build_param_size,
  :color  = _build_param_color,
  :height = 170 )
{ ... }

sub _build_param_color {
  return (qw(red green blue))[ int( rand 3 ) ];
}

# you can access all other parameters within a builder
sub _build_param_size {
  return $_{height} &gt; 200 ? 'large' : 'medium';
}
</code></pre>

<p><code>BuildArgs</code> can be used to preprocess <code>@_</code> before it is validated against the signature, and <code>CheckArgs</code> can be used to perform additional validation after the <code>%_</code> hash has been populated.</p>

<pre><code># preprocess @_ with buildargs
sub process_template
  :Args(input, output, params)
  :BuildArgs(_buildargs_process_template)
{
  say "open $_{input}";
  say "replace " . Dumper $_{params};
  say "save $_{output}";
}

# if 'output' is not provided, get it from input filename
sub _buildargs_process_template {
  if (@_ == 2) {
    my ($input, $params) = @_;
    my $output = $input;
    substr($output, -4, 4, "html");
    return $input, $output, $params;
  } else {
    return @_;
  }
}

my %data = (
  fname =&gt; "Foo",
  lname =&gt; "Bar",
);

process_template("index.tmpl", \%data);
# open index.tmpl
# replace {"lname" =&gt; "Bar", "fname" =&gt; "Foo"}
# save index.html

process_template("from.tmpl", "to.html", \%data);
# open from.tmpl
# replace {"lname" =&gt; "Bar", "fname" =&gt; "Foo"}
# save to.html

sub process_person
  :Args(:first_name!, :last_name!, :country!, :ssn?)
  :CheckArgs # shortcut for :CheckArgs(_checkargs_${subname})
{ ... }

sub _checkargs_process_person {
  if ( $_{country} eq 'USA' ) {
    die 'All US residents must have an SSN' unless $_{ssn};
  }
}
</code></pre>

<p>Most of the time you will use <code>MooseX::Params</code> in classes. Note the shortcut syntax to declare an invocant.</p>

<pre><code>package User;

use Moose;
use MooseX::Params;
use DateTime;

extends 'Person';

has 'password' =&gt; (
  is  =&gt; 'rw',
  isa =&gt; 'Str',
);

has 'last_login' =&gt; (
  is      =&gt; 'rw',
  isa     =&gt; 'DateTime',
);

sub login :Args(self: Str pw) {
  return 0 if $_{pw} ne $_{self}-&gt;password;

  $_{self}-&gt;last_login( DateTime-&gt;now() );

  return 1;
}
</code></pre>

<p>Read the full docs and <a href="http://search.cpan.org/dist/MooseX-Params/">get the latest version from CPAN</a> now (serious bugs are to be expected).</p>
</div></content>
	</entry>
 	
	<entry>
		<title>The Parameter Apocalypse, Take 2</title>
		<link href='http://mechanicalrevolution.com/blog/parameter_apocalypse_take_two.html' />
		<id>tag:mechanicalrevolution.com,2011-05-02:/parameter_apocalypse_take_two</id>
		<updated>2011-05-02T20:49:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This is a follow-up to my previous post at <a href="http://mechanicalrevolution.com/blog/parameter_apocalypse.html">http://mechanicalrevolution.com/blog/parameter_apocalypse.html</a>.</p>

<p>After experimenting with a lot of different ways to tackle method and parameter declaration, I think I have finally settled on an attributes-based interface that makes for a decent compromise between usability and compatibility. The examples blow describe the proposed interface. Note that only the <code>:Args</code> attribute is currently implemented.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This is a follow-up to my previous post at <a href="http://mechanicalrevolution.com/blog/parameter_apocalypse.html">http://mechanicalrevolution.com/blog/parameter_apocalypse.html</a>.</p>

<p>After experimenting with a lot of different ways to tackle method and parameter declaration, I think I have finally settled on an attributes-based interface that makes for a decent compromise between usability and compatibility. The examples blow describe the proposed interface. Note that only the <code>:Args</code> attribute is currently implemented.</p>

<!-- BREAK -->

<p>Subroutine attributes are evil, but still very convenient since they allow for a syntax that is clear and concise and does not depend on parser hooks. More importantly, if a <code>method</code> keyword is introduced in Perl 5.16, this syntax will be fully compatible with it too. I'd be glad to hear feedback from folks who have used attributes for larger projects and what kinds of issues they have encountered.</p>

<h2 id="parameterprocessing">Parameter processing</h2>

<p>A method is declared as plain perl subroutine, with optional <code>Args</code> attribute listing the accepted arguments:</p>

<pre><code>use Moose;
use MooseX::Params::Interface::Attributes;

sub doit :Args(first, second, third)
{
    # you can now use $_{first}, $_{second}, and $_{third}
}
</code></pre>

<p>The signature syntax is heavily influenced by Perl 6. Here is a more complicated example:</p>

<pre><code>sub doit :Args(Str first = "test", &amp;ArrayRef[Int] second?, :third = _build_param_third)
</code></pre>

<p>The basic rules are as follows:</p>

<ul>
<li>Parameter names are separated by commas.</li>
<li>A parameter name may be optionally preceded by a type constraint.</li>
<li>An ampersand ('&amp;') before a type constraint indicates that coercions associated with this constraint should be executed.</li>
<li>An exclamation mark (<code>!</code>) after a parameter name makes it required (all positional parameters are required by default).</li>
<li>A question mark (<code>?</code>) after a parameter name makes it optional.</li>
<li>An asterix (<code>*</code>) before a parameter name makes it slurpy, i.e. it will consume all remaining arguments and make them available in an arrayref.</li>
<li>All parameters are by default positional.</li>
<li>Named parameters have their name is preceded by a column.</li>
<li>A named parameter can be passed by a different name from the name under which it is availabe in <code>%_</code>: <code>:arg_name(real_name)</code>.</li>
<li>You can also have values in <code>%_</code> that cannot be passed as arguments at all: <code>:(real_name)</code> (you will have to supply a default value or builder).</li>
<li>An argument can have a default value introduced by the equals (<code>=</code>) sign.</li>
<li>The default value can be either a simple unsigned integer or a quoted string; both single and double quotes can be used to quote a string, but the string itself is always interpreted as if single quotes were used: i.e. no interpolation of variables or special characters takes place.</li>
<li>The default value can also be a valid perl identifier, optionally followed by brackets (<code>()</code>), which should be the name of an existing subroutine that will be used as a builder for this parameter. Such a builder will always be executed lazily, i.e. the first time the specified parameter is accessed.</li>
<li>If the equals sign is used but no subroutine name is provided, a builder named <code>_build_param_${param_name}</code> will be assumed. The following three are equivalent: <code>:third = _build_param_third</code>, <code>:third = _build_param_third()</code>, <code>:third=</code>.</li>
</ul>

<p>You can see working examples at <a href="http://cpansearch.perl.org/src/PSHANGOV/MooseX-Params-0.004/t/attributes/">http://cpansearch.perl.org/src/PSHANGOV/MooseX-Params-0.004/t/attributes/</a>.</p>

<p>You can also specify subroutines to pre-process and post-process arguments:</p>

<pre><code>sub doit :Args(first, second, third) 
         :BuildArgs(_buildargs_doit) 
         :CheckArgs(_checkargs_doit)
</code></pre>

<p><code>BuildArgs</code> is analogos to <code>BUILDARGS</code> for Moose constructors and points to a name of a subroutine that will pre-process arguments before they are validated. It can be used to coerce different types of arguments to the specified signature. If no subroutine name is provided to <code>BuildArgs</code>, <code>"_buildargs_${method_name}"</code> is assumed.</p>

<p><code>CheckArgs</code> is analogos to <code>BUILD</code> for Moose constructors and points to a name of a subroutine that will executed after all arguments have been processed. It can be used to perform complex argument checks that cannot be implemented by simple type constraints. If no subroutine name is provided to <code>CheckArgs</code>, <code>"_checkargs_${method_name}"</code> is assumed.</p>

<h2 id="returnvaluevalidation">Return value validation</h2>

<p>You can use the <code>Returns</code> attribute to specify a type constraint for the method's return value.</p>

<pre><code>sub doit :Args(first, second, third) :Returns(Str)
</code></pre>

<p>In order to valudate the return value, your code will always be executed in list context. If you want to return something special in scalar context, you can use the <code>ReturnsScalar</code> attribute, which allows you to choose a predifined behaviout in scalar context:</p>

<pre><code>sub doit :Args(first, second, third) :Returns(Array[Str]) :ReturnsScalar(ArrayRef)
</code></pre>

<p><code>ReturnScalar</code> may be one of <code>ArrayRef</code>, <code>First</code>, <code>Last</code> or <code>Count</code>. See <a href="http://search.cpan.org/dist/Attribute-Context/">http://search.cpan.org/dist/Attribute-Context/</a> for an explanation.</p>

<p>If  you want to do something really funny with context you should avoid using return value validation altogether.</p>

<h2 id="traits">Traits</h2>

<p>Subroutine traits are applied via the <code>Traits</code> attribute. Here is a hypothetical example of a subroutine that can be used as a subcommand with a custom name, and can accept two of its arguments from the command line:</p>

<pre><code>sub doit :Args(Str first, &amp;File second, :(third)=) 
         :Traits(Subcommand) 
         :SubcommandName(dothis)
         :SubcommandOpt(:f(first), :s(second))
</code></pre>

<h2 id="ordinaryfunctions">Ordinary functions</h2>

<p>A similar interface can be used for ordinary functions too:</p>

<pre><code>use MooseX::Params::Interface::Attributes::Module;

sub doit :Args(first, second, third) :Export(:DEFAULT)
</code></pre>

<p>See <a href="http://search.cpan.org/dist/Perl6-Export-Attrs/">http://search.cpan.org/dist/Perl6-Export-Attrs/</a> for export signature details.</p>
</div></content>
	</entry>
 	
	<entry>
		<title>MooseX::Params on CPAN</title>
		<link href='http://mechanicalrevolution.com/blog/moosex_params_on_cpan.html' />
		<id>tag:mechanicalrevolution.com,2011-04-03:/moosex_params_on_cpan</id>
		<updated>2011-04-03T23:00:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>An alpha versin of <a href="http://search.cpan.org/dist/MooseX-Params/">MooseX::Params</a>, described in <a href="http://mechanicalrevolution.com/blog/parameter_apocalypse.html">my previous post</a>, is already on CPAN. <a href="http://search.cpan.org/dist/MooseX-Params/">MooseX::Params</a> is an attempt to rethink parameter processing and function declaration in Perl. The current release implements the three main objectives: a meta protocol, parameters with lazy builders, and access to processed parameters via the <code>%_</code> hash.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>An alpha versin of <a href="http://search.cpan.org/dist/MooseX-Params/">MooseX::Params</a>, described in <a href="http://mechanicalrevolution.com/blog/parameter_apocalypse.html">my previous post</a>, is already on CPAN. <a href="http://search.cpan.org/dist/MooseX-Params/">MooseX::Params</a> is an attempt to rethink parameter processing and function declaration in Perl. The current release implements the three main objectives: a meta protocol, parameters with lazy builders, and access to processed parameters via the <code>%_</code> hash.</p>

<!-- BREAK -->

<p>I am now experimenting with different ways to make the syntax more concise and more perlish. I am looking into subroutine attributes, extra keywords and Devel::Declare. There are already have some cool ideas which I will share in an upcoming post. </p>
</div></content>
	</entry>
 	
	<entry>
		<title>My Perl 5.16 Parameter Processing Apocalypse</title>
		<link href='http://mechanicalrevolution.com/blog/parameter_apocalypse.html' />
		<id>tag:mechanicalrevolution.com,2011-03-10:/parameter_apocalypse</id>
		<updated>2011-03-10T22:41:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Change is happening and excitement is in the air. Perl 5.16 is gearing up to be a very inetersting release. And the one area where discussion is most heated is the last bastion of anti-modern Perl: method declarations and signatures.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Change is happening and excitement is in the air. Perl 5.16 is gearing up to be a very inetersting release. And the one area where discussion is most heated is the last bastion of anti-modern Perl: method declarations and signatures.</p>

<!-- BREAK -->

<p>It is said that writing an OO system is the rite of passage of every Perl programmer. Well, the advent of Moose has unfortunately sucked the life from this otherwise noble pastime. So, if a programmer wants to reinvent the wheel, the second best option remains writing a parameter processing library. There has been some increased recent activity on CPAN recently: Sub::Spec, Smart::Args, Sub::Args, Attribute::Args, Params::Check, to name a few, a testimony to how disempowering Perl's core functionality feels to programmers, and how difficult it is to choose the one true library to use. So, to make matters worse, I too have decided to present to the general public my take on parameter validation. </p>

<p>First, most of the examples below are just prototyping and do not really work yet. The main purpose of this post is to plan the API first and hopefully get some feedback. The github repo is at <a href="http://github.com/pshangov/moosex-params">http://github.com/pshangov/moosex-params</a>, but the code is of pre-alpha quality and is unlikely to see the light of CPAN soon. Currently supported are positional parameters, validation, dereferencing, localized <code>%_</code> and prototypes. Most of the cool things are yet to come ...</p>

<h2 id="primarygoals">Primary goals</h2>

<p>In the light of the discussions about the future of method declaration and parameter validation and instantiation for Perl 5.16+ it is my concern that no parameter processing library currently existing for Perl 5 goes far enough in tackling the problem, and this may affect the decisions taken for core Perl at this stage. Listed blow are the set of feature I believe such a library should have, with examples in the form of a sample implementation called MooseX::Params. The main features of this library are:</p>

<ol>
<li>Meta protocol for methods and parameters: this is where I find libraries such as Params::Validate and Params::Util inadequate, and MooseX::Method::Signatures lacking. A full meta protocol for parameters opens the door for many nifty features, not the least multi methods and extended role validation.</li>
<li>Extensibility: The method declaration and parameter processing syntax for Perl 6, partially implemented by MooseX::Method::Signatures, is widely considered as the way to go. I myself find this syntax pretty, but also very restrictive and difficult to extend. The analogy is the same as with Perl 6 attributes and Moose attributes: Perl 6 has a succinct syntax which is powerful, but it is based on punctuation to express meaning, and therefore adding new features is likely to entail adding new punctuation. Moose attributes are way more verbose to declare, but it is exceptionally simple to extend them with new properties via traits or metaclasses, and even add new keywords that encapsulate more complex behaviors. Denying this flexibility to method and parameter declaration would be a huge step backward for modern Perl 5 programming. </li>
<li>Compatible with other implementations: with a common underlying protocol it would be easy to choose a parameter processing library of your liking, and still play well with others. MooseX::Method::Signatures could easily be extended to support a large subset of what MooseX::Params aims to provide, so that you can use that if you want Devel:Declare goodness that is compatible with Perl 5.8, MooseX::Params if you prefer less magic in the libraries that you use, and whatever cool syntax is introduced in new Perls if you are allowed to use them in production.</li>
</ol>

<p>So far with the theory, on to the code.</p>

<h2 id="thebasics">The Basics</h2>

<p>MooseX::Params can be used just as ordinary Moose classes. Here is some code to start with:</p>

<pre><code>package Competition;

use MooseX::Params;

has 'sport' =&gt; ( is =&gt; 'ro', isa =&gt; 'Str', default =&gt; 'Running');

sub compete { ... }

sub pretty_print_ranking {
    my $self = shift;
    my ($first, $second, $third) = @_;

    say "Ranking for " . $self-&gt;sport . ":";
    say "***";
    say "First place: $first";
    say "Second place: $second";
    say "Third place: $third";
};
</code></pre>

<p>Executing</p>

<pre><code>$competition-&gt;pretty_print_ranking(qw(George Peter Jim));
</code></pre>

<p>prints:</p>

<pre><code>Ranking for Running:
***
First place: George
Second place: Peter
Third place: Jim
</code></pre>

<p>MooseX::Params exports a 'method' keyword for method declaration, so the above 'pretty_print_ranking' can also be written as follows:</p>

<pre><code>method 'pretty_print_ranking' =&gt; sub {
    my $self = shift;
    my ($first, $second, $third) = @_;

    say "Ranking for " . $self-&gt;sport . ":";
    say "***";
    say "First place: $first";
    say "Second place: $second";
    say "Third place: $third";
};
</code></pre>

<p>A trailing subref in the method declaration is really a shortcut for the following:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    execute =&gt; sub {
        my $self = shift;
        ...
    }
);
</code></pre>

<p>The argument to the 'execute' option can also be a string that points to a sub which will be used as the method body:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    execute =&gt; '_execute_pretty_print_ranking',
);

sub _execute_pretty_print_ranking {
    my $self = shift;
    ...
}
</code></pre>

<p>In fact, if you do not provide a trailing subref or an 'execute' option, your method would default to "<em>execute</em>$method_name":</p>

<pre><code>method 'pretty_print_ranking';

sub _execute_pretty_print_ranking {
    my $self = shift;
    ...
}
</code></pre>

<h2 id="parameters">Parameters</h2>

<p>You can declare parameters via the 'params' option, and later access them within the method body via the 'params' keyword:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [qw(first second third)],
    sub {
        my $self = shift;

        say "Ranking for " . $self-&gt;sport . ":";
        say "***";
        say "First place: "  . params 'first';
        say "Second place: " . params 'second';
        say "Third place: "  . params 'third';            
    }
);
</code></pre>

<p>All declared parameters have names, even if they are positional (the default). You can fetch either a simple parameter or a group of parameters at once:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [qw(first second third)],
    sub {
        my $self = shift;
        my ($first, $second, $third) = params qw(first second third);

        say "Ranking for " . $self-&gt;sport . ":";
        say "***";
        say "First place: $first";
        say "Second place: $second";
        say "Third place: $third";       
    }
);
</code></pre>

<p>MooseX::Params also declares two package globals in your class: <code>$self</code> and <code>%_</code>. Within every method invocation, $self is localized to the invocant, and <code>%_</code> is localized to a hash with the parameter as names, and parameter values as values:</p>

<p>(NOTE: this is kind of experimental since I am not sure of all of its possible implications yet)</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [qw(first second third)],
    sub {
        say "Ranking for " . $self-&gt;sport . ":";
        say "***";
        say "First place: $_{first}";
        say "Second place: $_{second}";
        say "Third place: $_{third}";            
    }
);
</code></pre>

<h2 id="parameteroptions">Parameter options</h2>

<p>The concept of parameters is heavily influenced by Moose attributes. Method parameters act as a complement to object attributes and allow you to build even more powerful APIs with greater separation of concerns:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        first  =&gt; { isa =&gt; 'Str', required =&gt; 1 },
        second =&gt; { isa =&gt; 'Str', required =&gt; 1 },
        third  =&gt; { isa =&gt; 'Str', required =&gt; 1 },
    ],
    sub {
        say "Ranking for " . $self-&gt;sport . ":";
        say "***";
        say "First place: $_{first}";
        say "Second place: $_{second}";
        say "Third place: $_{third}";            
    }
);
</code></pre>

<p>Supported options borrowed from Moose attributes:</p>

<ul>
<li>isa</li>
<li>required</li>
<li>coerce</li>
<li>init_arg (applies to named parameters only)</li>
<li>auto_deref</li>
<li>default</li>
<li>builder</li>
<li>lazy</li>
<li>lazy_build</li>
<li>traits</li>
<li>weak_ref</li>
</ul>

<p>Some of them are more interesting than the others, so we will focus on them here.</p>

<h2 id="autodereferencing">Auto dereferencing</h2>

<p>You ham specify that a parameter should be automatically dereferenced when requested from 'params'. Let us modify the interface to 'pretty_print_ranking' a little:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport =&gt; { 
            isa      =&gt; 'Str', 
            required =&gt; 1, 
            default  =&gt; 'Running' 
        },
        winners =&gt; { 
            isa        =&gt; 'ArrayRef[Str]', 
            required   =&gt; 1, 
            auto_deref =&gt; 1 
        },
    ],
    sub {
        say "Ranking for " . params('sport') . ":";
        say "***";

        my @places = qw(First Second Third);
        my $i = 0;

        foreach my $winner ( params('winners') )
        {
            say $places[$i] . " place: $winner";
            last if ++$i &gt;= 3;
        }
    }
);
</code></pre>

<p>A parameter will auto dereference only if it is the only or last parameter requested from 'params':</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    ...
    sub { 
        my ($sport, $first, $second, $last) = params qw(sport winners);
        ...
    }
};
</code></pre>

<h2 id="builders">Builders</h2>

<p>Builders are a powerful feature that greatly aids in separation of concerns:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport  =&gt; { ... },
        winners =&gt; { 
            ...
            lazy_build =&gt; 1,
        },
    ],
    sub { ... }
);
</code></pre>

<p>The builder method has access to both the method invocant and to the arguments hash with the parameters processed so far:</p>

<pre><code>sub _build_param_winners
{
    return [ $self-&gt;compete($_{sport}) ];
}
</code></pre>

<h2 id="traits">Traits</h2>

<p>Traits are the main point of extensibility for methods and parameters. Imagine a method that is a subcommand in a larger command line application (think App::Cmd), and you want to separate command-line arguments applicable to the whole app from command-line arguments applicable only to a specific subcommand:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport =&gt; { 
            traits   =&gt; [qw(Getopt)],
            cmd_flag =&gt; 'sport',
            ...
        },
        winners =&gt; { ... },
    ],
    sub { ... }
);

shell:~# competition pretty_print_ranking --sport Running
</code></pre>

<h2 id="namedvs.positional">Named vs. positional</h2>

<p>Parameters are by default positional. If you want your arguments passed as a hash, you should explicitly request that:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        first  =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named' },
        second =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named' },
        third  =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named' },
    ],
    sub {
        ...          
    }
);
</code></pre>

<p>Now you can call your method like that:</p>

<pre><code>$competition-&gt;pretty_print_ranking(
    first  =&gt; 'George',
    second =&gt; 'Peter',
    third  =&gt; 'Jim',
);
</code></pre>

<p>Since large applications tends to use a consistent style of parameter passing, you can change the defaults on a per-class basis:</p>

<pre><code>use MooseX::Params -named;

method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport  =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'positional' },
        first  =&gt; { isa =&gt; 'Str', required =&gt; 1 },
        second =&gt; { isa =&gt; 'Str', required =&gt; 1 },
        third  =&gt; { isa =&gt; 'Str', required =&gt; 1 },
    ],
    sub {
        ...          
    }
);

$competition-&gt;pretty_print_ranking( 'Jumping',
    first  =&gt; 'George',
    second =&gt; 'Peter',
    third  =&gt; 'Jim',
);
</code></pre>

<p>As seen above, named arguments can mix with positional arguments, as long as all positional arguments are required and come first. Other calling styles are available too, with the goal being to support most styles currently in use:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport  =&gt; { isa =&gt; 'Str', required =&gt; 1 },
        first  =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named_ref' },
        second =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named_ref' },
        third  =&gt; { isa =&gt; 'Str', required =&gt; 1, type =&gt; 'named_ref' },
    ],
    sub {
        ...          
    }
);

$competition-&gt;pretty_print_ranking( 'Jumping', {
    first  =&gt; 'George',
    second =&gt; 'Peter',
    third  =&gt; 'Jim',
});
</code></pre>

<h2 id="predeclaredparameters">Predeclared parameters</h2>

<p>A large library will often use a limited number of common parameter types. E.g. most widget creation methods in a GUI library such as Tk would accept similar parameters such as 'background', 'foreground', 'position', 'padding', 'label', etc. MooseX::Params allows you to predeclare parameters and reuse them across methods:</p>

<pre><code>param 'first' =&gt; (
    isa      =&gt; 'Str',
    required =&gt; 1,
);

param 'second' =&gt; (
    isa      =&gt; 'Str',
    required =&gt; 1,
);

param 'third' =&gt; (
    isa      =&gt; 'Str',
    required =&gt; 1,
);

method 'pretty_print_ranking' =&gt; (
    params =&gt; [qw(first second third)],
    sub { ... },
}
</code></pre>

<p>You can modify pre-declared parameters when needed:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        '+first'  =&gt; { type =&gt; 'named'},
        '+second' =&gt; { type =&gt; 'named'},
        '+third'  =&gt; { type =&gt; 'named'},
    ],
    sub { ... },
}
</code></pre>

<h2 id="slurpyparameters">Slurpy parameters</h2>

<p>Slurpy parameters come last and consume the remained of the parameter list:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params =&gt; [
        sport =&gt; { 
            isa      =&gt; 'Str', 
            required =&gt; 1, 
            default  =&gt; 'Running' 
        },
        winners =&gt; { 
            isa        =&gt; 'Array[Str]', 
            required   =&gt; 1, 
            auto_deref =&gt; 1,
            slurpy     =&gt; 1,
        },
    ],
    sub { ... }
);

$competition-&gt;pretty_print_ranking(qw(Jumping George Peter Jim));
</code></pre>

<h2 id="returnvalues">Return values</h2>

<p>Methods can be declared with other attributes besides 'param'. The most important probably is the specification of the return value:</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    params  =&gt; [ ... ],
    returns =&gt; 'Str',
    sub { 
        my $printout = "Ranking for " . $self-&gt;sport . ":\n";
        $printout .= "***\n";
        $printout .= "First place: $_{first}";
        $printout .= "Second place: $_{second}";
        $printout .= "Third place: $_{third}";

        return $printout;
    },
);
</code></pre>

<p>The constraints for slurpy parameters can also be used to validate non-scalar return values. The compete method returns a list of the winners of the first three places:</p>

<pre><code>method 'compete' =&gt; (
    returns =&gt; 'Array[Str]',
    ...
);
</code></pre>

<p>We can also validate return output according to context. Imagine that in scalar context our 'compete' method only returns the winner of the first place:</p>

<pre><code>method 'compete' =&gt; (
    returns =&gt; { scalar =&gt; 'Str', list =&gt; 'Array[Str]' },
    ...
);
</code></pre>

<h2 id="prototypes">Prototypes</h2>

<p>You can also specify prototypes (although if you want to do that you will probably want to use a lower level syntax for subroutine declaration):</p>

<pre><code>method 'pretty_print_ranking' =&gt; (
    prototype =&gt; '@',
    ...
);
</code></pre>

<h2 id="traits">Traits</h2>

<p>Methods can have traits too:</p>

<pre><code>method '_pretty_print_ranking' =&gt; (
    traits  =&gt; [qw(Private Static Memoized)],
    returns =&gt; 'Str',
    ...
);

method 'pretty_print_ranking' =&gt; (
    traits   =&gt; [qw(Subcommand)],
    cmd_flag =&gt; 'results',
    params =&gt; [
        sport =&gt; { 
            traits   =&gt; [qw(Getopt)],
            cmd_flag =&gt; 'sport',
            ...
        },
        ...
    ],
    sub { print __PACKAGE__-&gt;_pretty_print_ranking }
);

shell:~# competition results --sport Running
</code></pre>

<h2 id="extendedrolerequirements">Extended role requirements</h2>

<p>Since methods know about their parameters and return values, roles can be more picky about what they accept:</p>

<pre><code>package RankingPrettyPrinter;

use Moose::Role;
use MooseX::Params;

requires 'sport'   =&gt; { returns =&gt; 'Str' };
requires 'compete' =&gt; { returns =&gt; 'Array[Str]' };

method 'pretty_print_ranking' =&gt; (
    params =&gt; [ winners =&gt; { lazy_buld =&gt; 1, ...} ],
    sub { ... },
);

sub _build_param_winners {
    return [ $self-&gt;compete($self-&gt;sport) ];
}
</code></pre>

<h2 id="mutlimethods">Mutlimethods</h2>

<p>We can do multimethods too. Here is the classic rock, paper, scissors game:</p>

<pre><code>package RockPaperScissors;

use MooseX::Params;

param 'rock'     =&gt; ( isa =&gt; subtype( 'Str' =&gt; where { $_ eq 'Rock'     } ) );
param 'paper'    =&gt; ( isa =&gt; subtype( 'Str' =&gt; where { $_ eq 'Paper'    } ) );
param 'scissors' =&gt; ( isa =&gt; subtype( 'Str' =&gt; where { $_ eq 'Scissors' } ) );

multi method 'play' =&gt; ( params =&gt; [qw(paper rock)],     sub { 1 } );
multi method 'play' =&gt; ( params =&gt; [qw(scissors paper)], sub { 1 } );
multi method 'play' =&gt; ( params =&gt; [qw(rock scissors)],  sub { 1 } );
multi method 'play' =&gt; ( sub { 0 } );
</code></pre>

<h2 id="modules">Modules</h2>

<p>And last but not least, most of these features are also available to plain functions: </p>

<pre><code>package RankingPrettyPrinter;

use MoooseX::Params::Module;

function 'pretty_print_ranking' =&gt; (
    export_ok   =&gt; 1,
    export_tags =&gt; [qw(:all :print)],
    params      =&gt; [qw(sport winners)],
    execute     =&gt; sub { ... }
);
</code></pre>

<h2 id="howthisallrelatestoperl5.16">How this all relates to Perl 5.16</h2>

<p>So far so good, but how does all this relate to the future development of Perl 5? Well, the above examples may be powerful, but with brackets and arrows galore they sure ain't beautiful. However, I don't think Perl 5.16+ necessarily needs to add a bunch of new keywords and fix them in core for generations to come in order to improve the situation. Here is a beautified example of some of the above code: </p>

<pre><code>package Competition 0.001 isa Moose::Class;

method pretty_print_ranking
    param sport   { isa =&gt; 'Str',        qo(:required) }
    param winners { isa =&gt; 'Array[Str]', qo(:required :auto_deref :slurpy) }
    returns 'Str'
{
    my $printout = "Ranking for $_{sport} :\n";
    ...
    return $printout;         
}
</code></pre>

<p>So let us tranport ourselves an year in the future and look at some hypothetical features in the very-soon-to-be-released Perl 5.16 that would make this syntax possible:</p>

<p>First, the sugary package declaration:</p>

<pre><code>package XXX isa YYY;
</code></pre>

<p>This is esentially equivalent to:</p>

<pre><code>package XXX:
use YYY;
</code></pre>

<p>except that it makes it explicitly clear what type of package we are dealing with ('isa' is probably not the most appropriate keyword here but it illustrates the example well). Example uses:</p>

<pre><code>package XXX isa Moose::Class;
package XXX isa Moose::Role;
package XXX isa Catalyst::Controller;
package XXX isa App::Cmd;
package XXX isa Regexp::Grammar;
</code></pre>

<p>Next, some new subroutine prototypes. Most importantly, we need prorotypes that can also hint the parser where to end and expression or a statement. In the fictitious examples below:</p>

<ul>
<li><code>"$"</code> is a prototype for a bareword identifier that does not need to be followed by a comma</li>
<li><code>\%</code> is a prototype for a hashref</li>
<li><code>@[\%]</code> is a prototype for an array of hashrefs</li>
<li><code>,</code> is an expression-ending prototype (works if the last argument to the sub can always be reliably determined) so that we do not have to insert commas after the function invocation</li>
<li><code>;</code> is a statement-ending prototype (works if the last argument to the sub can always be reliably determined) so that we do not have to insert a semi-column after the function invocation</li>
<li><code>&amp;</code> is ye old code prototype</li>
</ul>

<p>With them we can declare:</p>

<pre><code>sub param    ("$"\%,)     # bareword, hashref and expression end
sub returns  ($,)         # scalar and expression end
sub method   ("$"@[\%]&amp;;) # bareword, array of hashrefs ('param' and 'returns' will return hashref-based objects), code and statement end
</code></pre>

<p>And last but not least there is the 'quote options' operator:</p>

<pre><code>qo(:required :auto_deref :slurpy) == ( required =&gt; 1, auto_deref =&gt; 1, slurpy =&gt; 1 );
</code></pre>

<p>Of course I know little about how Perl's parser works and I don't know how possible it is to add such features to the core. I like to think, however, that Perl still has a lot of room to evolve by building on established idioms rather than introducing radical new concepts.</p>

<p>Thank you for bearing with my little language design exercise, please comment if you find it interesting!</p>
</div></content>
	</entry>
 	
	<entry>
		<title>Bulgarian Perl Workshop</title>
		<link href='http://mechanicalrevolution.com/blog/bg_perl_2011.html' />
		<id>tag:mechanicalrevolution.com,2011-02-21:/bg_perl_2011</id>
		<updated>2011-02-21T22:34:00+00:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This year's Bulgarian Perl Workshop is taking place in Sofia on Saturday, February 26. With the help of the French Perl Mongers we will have a <a href="http://perldancer.org/">Dancer</a> talk by Alexis Sukrieh, and we are also excited to have Alex Kapranoff from Moscow.pm as a guest speaker. The event is off to a great start, and we even have some fantastic artwork thanks to our friends at <a href="http://designfield.biz/">designfield.biz</a>. More details are available at the workshop website <a href="http://perlbulgaria.org">perlbulgaria.org</a>.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>This year's Bulgarian Perl Workshop is taking place in Sofia on Saturday, February 26. With the help of the French Perl Mongers we will have a <a href="http://perldancer.org/">Dancer</a> talk by Alexis Sukrieh, and we are also excited to have Alex Kapranoff from Moscow.pm as a guest speaker. The event is off to a great start, and we even have some fantastic artwork thanks to our friends at <a href="http://designfield.biz/">designfield.biz</a>. More details are available at the workshop website <a href="http://perlbulgaria.org">perlbulgaria.org</a>.</p>

<!-- BREAK -->

<p><img src="/files/bg-perl-workshop-2011.png" alt="Bulgarian Perl Workshop" id="bulgarianperlworkshop" /></p>
</div></content>
	</entry>
 	

</feed>

