<?xml version="1.0" encoding="iso-8859-1"?>
 
<feed xmlns="http://www.w3.org/2005/Atom">
 
	<title>Atom Feed</title>
	<link href='http://www.mechanicalrevolution.com/feed.xml' rel="self" />
	<id>tag:www.mechanicalrevolution.com,2011-07-06:/list/feed</id>
	<updated>2011-07-06T21:05:14+03:00</updated>
	<author>
		<name>Your Name</name>
	</author>
 	
	
	<entry>
		<title>Catalyst::Model::FormFu</title>
		<link href='http://www.mechanicalrevolution.com/blog/catalyst_model_formfu.html' />
		<id>tag:www.mechanicalrevolution.com,2011-07-06:/catalyst_model_formfu</id>
		<updated>2011-07-06T21:03:29+03: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://www.mechanicalrevolution.com/blog/perl_names_and_world_domination.html' />
		<id>tag:www.mechanicalrevolution.com,2011-06-29:/perl_names_and_world_domination</id>
		<updated>2011-06-29T22:27:46+03: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://www.mechanicalrevolution.com/blog/my_darkpan_setup.html' />
		<id>tag:www.mechanicalrevolution.com,2011-06-19:/my_darkpan_setup</id>
		<updated>2011-06-19T23:21:10+03: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://www.mechanicalrevolution.com/blog/moosex_params_usage_examples.html' />
		<id>tag:www.mechanicalrevolution.com,2011-06-14:/moosex_params_usage_examples</id>
		<updated>2011-06-14T00:04:58+03: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://www.mechanicalrevolution.com/blog/parameter_apocalypse_take_two.html' />
		<id>tag:www.mechanicalrevolution.com,2011-05-02:/parameter_apocalypse_take_two</id>
		<updated>2011-05-02T20:49:21+03: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://www.mechanicalrevolution.com/blog/moosex_params_on_cpan.html' />
		<id>tag:www.mechanicalrevolution.com,2011-04-03:/moosex_params_on_cpan</id>
		<updated>2011-04-03T23:00:15+03: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://www.mechanicalrevolution.com/blog/parameter_apocalypse.html' />
		<id>tag:www.mechanicalrevolution.com,2011-03-10:/parameter_apocalypse</id>
		<updated>2011-03-10T23:41:20+03: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://www.mechanicalrevolution.com/blog/bg_perl_2011.html' />
		<id>tag:www.mechanicalrevolution.com,2011-02-21:/bg_perl_2011</id>
		<updated>2011-02-21T23:34:28+03: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>
 	
	<entry>
		<title>HTML::FormFu, The Missing Manual</title>
		<link href='http://www.mechanicalrevolution.com/blog/html_formfu_manual.html' />
		<id>tag:www.mechanicalrevolution.com,2010-12-12:/html_formfu_manual</id>
		<updated>2010-12-12T20:42:44+03:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://search.cpan.org/perldoc?HTML::FormFu">HTML::FormFu</a> is a fantastic library for managing web forms. It is a very flexible framework to create and validate forms, and it also provides powerful tools to fetch and update form data from and into a database. Having already used it for a number of application at $work (in conjunction with Catalyst and DBIx::Class), I have been truly amazed by the improvement it has brought in terms of both speed of development and clarity of code.</p>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p><a href="http://search.cpan.org/perldoc?HTML::FormFu">HTML::FormFu</a> is a fantastic library for managing web forms. It is a very flexible framework to create and validate forms, and it also provides powerful tools to fetch and update form data from and into a database. Having already used it for a number of application at $work (in conjunction with Catalyst and DBIx::Class), I have been truly amazed by the improvement it has brought in terms of both speed of development and clarity of code.</p>

<!-- BREAK -->

<p>Unfortunately HTML::FormFu's complicated and somewhat scattered documentation creates a steep learning curve and makes it daunting for beginners to appreciate its full power and flexibility. Indeed <a href="http://cpanratings.perl.org/dist/HTML-FormFu">almost all reviews on CPAN Ratings</a> mention as their primary concern that the docs needs improving. Therefore I am proud to present the brand new <a href="http://search.cpan.org/perldoc?HTML::FormFu::Manual">HTML::FormFu::Manual</a>, which has been specifically designed to explain the basic concepts of HTML::FormFu in a clear and beginner-friendly manner, and to allow new users to get up to speed with its powerful features as fast as possible.</p>

<p><a href="http://search.cpan.org/perldoc?HTML::FormFu::Manual">Check it out on CPAN now!</a></p>
</div></content>
	</entry>
 	
	<entry>
		<title>pmhack, podpreview, rcsync</title>
		<link href='http://www.mechanicalrevolution.com/blog/pmhack_podpreview_rcsync.html' />
		<id>tag:www.mechanicalrevolution.com,2010-09-29:/pmhack_podpreview_rcsync</id>
		<updated>2010-09-29T22:03:04+03:00</updated>
		<summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>I finally got to package some of my automation scripts as proper distributions and upload them to CPAN in the hope that somebody else may find them useful too.</p>

<h2 id="pmhackhttp:search.cpan.orgperldocpmhack"><a href="http://search.cpan.org/perldoc?pmhack">pmhack</a></h2>

<p>Usage:</p>

<pre><code>pmhack Some::Module::Name
</code></pre>
</div></summary>
		<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>I finally got to package some of my automation scripts as proper distributions and upload them to CPAN in the hope that somebody else may find them useful too.</p>

<h2 id="pmhackhttp:search.cpan.orgperldocpmhack"><a href="http://search.cpan.org/perldoc?pmhack">pmhack</a></h2>

<p>Usage:</p>

<pre><code>pmhack Some::Module::Name
</code></pre>

<!-- BREAK -->

<p>This app makes it easy to make a copy of an installed module from its original location in @INC to a directory where you can safely hack on it. In order to use it, you need to set an environment variable PERL5HACKLIB which points to a directory where modules will be copied. You also need to add the directory from PERL5HACKLIB to PERL5LIB, so that the new version of the module will be used instead of the original one. pmhack takes care of creating all necessary directories, copying the file and making it writable. On success it prints the path to the newly copied module, so you can do:</p>

<pre><code>vim `pmhack Some::Module::Name`
</code></pre>

<h2 id="podpreviewhttp:search.cpan.orgperldocpodpreview"><a href="http://search.cpan.org/perldoc?podpreview">podpreview</a></h2>

<p>Usage:</p>

<pre><code>podpreview path/to/pod/file
</code></pre>

<p>This app converts a file containing POD into html and launches a browser do display it. I wrote it primarily because I find it easier to spot errors or discrepancies in a POD document when viewing it as html. Now I can do the following in vim while editing a file:</p>

<pre><code>:!podpreview %
</code></pre>

<h2 id="rcsynchttp:search.cpan.orgperldocrcsync"><a href="http://search.cpan.org/perldoc?rcsync">rcsync</a></h2>

<p>Usage:</p>

<pre><code>rcsync profile1 profile2
</code></pre>

<p>This is an app I wrote to help me sync my configuration files across the different machines where I work (my office computer, my home computer and my laptop). For each configuration file, I create a template which contains the settings that will be common across all machines, and for any settings that are machine-specific, e.g. file paths, I use template variables. All templates are stored in a common directory, which I keep in sync via a free private git repo from Assembla. On each machine there is a ~/.rcsync configuration file that contains information about how each template should be deployed: the file where it should be written and the variables that it should be passed. These settings are organized in "profiles". Currently one profile corresponds to one configuration file, but this will change and in the future you will be able to sync multiple files and directories via a single profile (e.g. .vimrc and vim plugins via a "vim" profile). So for example, if I want to make a change to my local .vimrc, whose settings I have configured in a profile called "vim", I would make edit directly the template file and then run <code>rcsync vim</code> to deploy it. Afterwards when I am on a different machine I would run <code>git pull</code> on the templates directory and then <code>rcsync vim</code> to update my .vimrc there, or <code>rcsync --all</code> to apply updates to all profiles.</p>
</div></content>
	</entry>
 	

</feed>



