--- 
author: 
  email: rafl@fsfe.org
  keyid: 742f2a428e635a5e
  name: Florian Ragwitz
categories: 
  - Perl
date: 2009-08-19T08:27:25Z
guid: a9b71ca9-4050-4322-9afe-2f5e2ee9a776
modified: 2009-08-19T08:27:25Z
raw: "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\n=pod\n\nYou've probably already heard of Sartak's awesome\nL<MooseX::Role::Parameterized|http://search.cpan.org/perldoc?MooseX::Role::Parameterized>.\n\nAs of version 0.25, MooseX::Declare provides some nice sugar for\nthat. This is what it looks like:\n\n  lang:Perl\n  use MooseX::Declare;\n\n  role Counter (Str :$name) {\n    has $name => (is => 'rw', isa => 'Int', default => 0);\n\n    method \"increment_${name}\" {\n      $self->$name( $self->$name + 1 );\n    }\n\n    method \"reset_${name}\" {\n      $self->$name(0);\n    }\n  }\n\n  class MyGame::Weapon {\n    with Counter => { name => 'enchantment' };\n  }\n\n  class MyGame::Wand {\n    with Counter => { name => 'zapped' };\n  }\n\nJust thought I'd let you know, since i haven't gotten around to\nactually document this. In case you like it, have some spare\ntuits, and want to help out, the repository is\nL<right here|git://github.com/rafl/moosex-declare.git> :-)\n\n=cut\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.6 (GNU/Linux)\n\niD8DBQFKi7dGdC8qQo5jWl4RAkm2AJ9m1S3kzkHl1zgMQfh2bU9pqFLnVwCcCNpN\nEMIF5I5VMLWrpy/ESf3Bs14=\n=9SN1\n-----END PGP SIGNATURE-----\n"
signed: 1
summary: " You've probably already heard of Sartak's awesome MooseX::Role::Pa- rameterized. …"
tags: 
  - 
    perl: 0
  - 
    moose: 0
  - 
    syntax: 0
text: "    You've probably already heard of Sartak's awesome MooseX::Role::Pa-\n    rameterized.\n\n    As of version 0.25, MooseX::Declare provides some nice sugar for\n    that. This is what it looks like:\n\n      lang:Perl use MooseX::Declare;\n\n      role Counter (Str :$name) { has $name => (is => 'rw', isa => 'In-\n      t', default => 0);\n\n        method \"increment_${name}\" { $self->$name( $self->$name + 1 ); }\n\n        method \"reset_${name}\" { $self->$name(0); } }\n\n      class MyGame::Weapon { with Counter => { name => 'enchant-\n      ment' }; }\n\n      class MyGame::Wand { with Counter => { name => 'zapped' }; }\n\n    Just thought I'd let you know, since i haven't gotten around to ac-\n    tually document this. In case you like it, have some spare tuits,\n    and want to help out, the repository is right here :-)\n"
title: Parameterized Roles with MooseX::Declare
type: pod
uri: http://perldition.org/articles/Parameterized%20Roles%20with%20MooseX%3A%3ADeclare.pod
xhtml: "<div class=\"pod\">\n<p>You've probably already heard of Sartak's awesome\n<a href=\"http://search.cpan.org/perldoc?MooseX::Role::Parameterized\">MooseX::Role::Parameterized</a>.</p>\n<p>As of version 0.25, MooseX::Declare provides some nice sugar for\nthat. This is what it looks like:</p>\n<pre><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Declare</span><span class=\"Normal\">;</span>\n\n<span class=\"Normal\">role Counter (Str :</span><span class=\"DataType\">$name</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">  has </span><span class=\"DataType\">$name</span><span class=\"Normal\"> =&gt; (is =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">rw</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, isa =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">Int</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, default =&gt; 0);</span>\n\n<span class=\"Normal\">  method </span><span class=\"Operator\">&quot;</span><span class=\"String\">increment_</span><span class=\"DataType\">${name}</span><span class=\"Operator\">&quot;</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"DataType\">$self</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">$name</span><span class=\"Normal\">( </span><span class=\"DataType\">$self</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">$name</span><span class=\"Normal\"> + </span><span class=\"Float\">1</span><span class=\"Normal\"> );</span><span class=\"Normal\">\n</span><span class=\"Normal\">  }</span>\n\n<span class=\"Normal\">  method </span><span class=\"Operator\">&quot;</span><span class=\"String\">reset_</span><span class=\"DataType\">${name}</span><span class=\"Operator\">&quot;</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"DataType\">$self</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">$name</span><span class=\"Normal\">(0);</span><span class=\"Normal\">\n</span><span class=\"Normal\">  }</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n\n<span class=\"Normal\">class </span><span class=\"Function\">MyGame::Weapon</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">  with Counter =&gt; { name =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">enchantment</span><span class=\"Operator\">&apos;</span><span class=\"Normal\"> };</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n\n<span class=\"Normal\">class </span><span class=\"Function\">MyGame::Wand</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">  with Counter =&gt; { name =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">zapped</span><span class=\"Operator\">&apos;</span><span class=\"Normal\"> };</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n</pre>\n<p>Just thought I'd let you know, since i haven't gotten around to\nactually document this. In case you like it, have some spare\ntuits, and want to help out, the repository is\n<a href=\"git://github.com/rafl/moosex-declare.git\">right here</a> :-)</p>\n\n\n</div>"
--- 
author: 
  email: rafl@fsfe.org
  keyid: 742f2a428e635a5e
  name: Florian Ragwitz
categories: 
  - Perl
date: 2009-05-08T22:51:11Z
guid: 7f51c642-13c4-43aa-80c9-73663b73fe9c
modified: 2009-05-08T22:53:28Z
raw: "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\n=pod\n\nI've been doing some contracting work for L<10gen|http://10gen.com>\nrecently. They have that rather cool open source document database\ncalled L<MongoDB|http://mongodb.org> and they wanted me to write a\nmodule to use that from Perl. I did that and the code is now available\non L<CPAN|http://search.cpan.org/dist/MongoDB> and\nL<github|http://github.com/mongodb/mongo-perl-driver>.\n\nWriting that was fun, and I'm already looking forward to be able to\nuse MongoDB as a backend for\nL<KiokuDB|http://search.cpan.org/perldoc?KiokuDB>. I started writing\ncode for that and put it on\nL<github|http://github.com/rafl/kiokudb-backend-mongodb>, but isn't\npassing all the tests just yet.\n\nIn related news, after finishing the MongoDB module, I'm available for\nother things again. So if you're looking for a\nL<Perl telecommuter|http://search.cpan.org/~flora/>,\nL<let me know|mailto:rafl@debian.org>.\n\n=cut\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.6 (GNU/Linux)\n\niD8DBQFKBLfodC8qQo5jWl4RAmVhAJ91KsH6+CX0i54MXm687lEjUs0rZwCeL4Nf\nwqzK9jT9aW7oWwnb6lKfbzQ=\n=dAd5\n-----END PGP SIGNATURE-----\n"
signed: 1
summary: " I've been doing some contracting work for 10gen recently. …"
tags: 
  - 
    perl: 0
  - 
    kiokudb: 0
  - 
    mongodb: 0
text: "    I've been doing some contracting work for 10gen recently. They have\n    that rather cool open source document database called MongoDB and\n    they wanted me to write a module to use that from Perl. I did that\n    and the code is now available on CPAN and github.\n\n    Writing that was fun, and I'm already looking forward to be able to\n    use MongoDB as a backend for KiokuDB. I started writing code for\n    that and put it on github, but isn't passing all the tests just yet.\n\n    In related news, after finishing the MongoDB module, I'm available\n    for other things again. So if you're looking for a Perl telecom-\n    muter, let me know.\n"
title: MongoDB on CPAN
type: pod
uri: http://perldition.org/articles/MongoDB%20on%20CPAN.pod
xhtml: "<div class=\"pod\">\n<p>I've been doing some contracting work for <a href=\"http://10gen.com\">10gen</a>\nrecently. They have that rather cool open source document database\ncalled <a href=\"http://mongodb.org\">MongoDB</a> and they wanted me to write a\nmodule to use that from Perl. I did that and the code is now available\non <a href=\"http://search.cpan.org/dist/MongoDB\">CPAN</a> and\n<a href=\"http://github.com/mongodb/mongo-perl-driver\">github</a>.</p>\n<p>Writing that was fun, and I'm already looking forward to be able to\nuse MongoDB as a backend for\n<a href=\"http://search.cpan.org/perldoc?KiokuDB\">KiokuDB</a>. I started writing\ncode for that and put it on\n<a href=\"http://github.com/rafl/kiokudb-backend-mongodb\">github</a>, but isn't\npassing all the tests just yet.</p>\n<p>In related news, after finishing the MongoDB module, I'm available for\nother things again. So if you're looking for a\n<a href=\"http://search.cpan.org/~flora/\">Perl telecommuter</a>,\n<a href=\"mailto:rafl@debian.org\">let me know</a>.</p>\n\n\n</div>"
--- 
author: 
  email: rafl@fsfe.org
  keyid: 742f2a428e635a5e
  name: Florian Ragwitz
categories: 
  - Perl
date: 2009-04-29T15:20:03Z
guid: 13d6b55d-2935-43fe-a0fd-bfba692b06a0
modified: 2009-04-29T15:22:37Z
raw: "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\n=pod\n\nLots of CPAN distributions require some kind of graphical\nenvironment. Some of them even pop up windows, which not only very\nannoying, but also sometimes fails if you're using a tiled window\nmanager.\n\nTo test such distributions on a machine where no graphical environment\nis available or on your desktop while you're working and don't want to\nget annoyed to death you can use a fake X server, like Xvfb.\n\nThe easiest way to do that is to run\n\n  lang:Bash\n  $ xvfb-run -a make test\n\ninstead of a plain C<make test>. That'll automatically create a fake\nxserver, set up C<DISPLAY> and run C<make test> in that environment.\n\nThat works well for manually installing modules. When installing using\nC<CPAN.pm> you can make things easier by writing a distropref.\n\nFirst, tell cpan where your distroprefs are. I use C<~/.cpan/prefs>:\n\n  lang:Bash\n  $ cpan\n  cpan[1]> o conf init prefs_dir\n  [...]\n  <prefs_dir>\n  Directory where to store default options/environment/dialogs for\n  building modules that need some customization? [] /home/rafl/.cpan/prefs\n  cpan[3]> o conf commit\n  commit: wrote '/home/rafl/.cpan/CPAN/MyConfig.pm'\n\nNow write a distropref for the modules that need an X server and put\nit into your prefs dir as C<X11.yml>\n\n  ---\n  match:\n    distribution: |\n      /(?x:Wx\n        |Gtk2\n        |Gnome2\n        |... other modules requiring an X server\n      )-\\d|\n  test:\n    commandline: \"xvfb-run -a make test\"\n\nNow the tests for Wx, Gtk2, Gnome2 and all other distributions you\nlist in that regex will be executed with a fake X server.\n\nI have yet to figure out how to write a distropref that just prepends\nto the test commandline instead of replacing it so I won't need to\nhave another pref for all modules using C<Module::Build>.\n\n=cut\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.6 (GNU/Linux)\n\niD8DBQFJ+HC9dC8qQo5jWl4RAl7JAJ4y9ubdkzkHw1fiH0gZYeKZG1Xm2wCfWY/P\nXj+fmSrSkoESejt0Cpykoms=\n=FtHr\n-----END PGP SIGNATURE-----\n"
signed: 1
summary: " Lots of CPAN distributions require some kind of graphical …"
tags: 
  - 
    perl: 0
  - 
    cpan: 0
text: "    Lots of CPAN distributions require some kind of graphical envi-\n    ronment. Some of them even pop up windows, which not only very\n    annoying, but also sometimes fails if you're using a tiled win-\n    dow manager.\n\n    To test such distributions on a machine where no graphical environ-\n    ment is available or on your desktop while you're working and don't\n    want to get annoyed to death you can use a fake X server, like Xvfb.\n\n    The easiest way to do that is to run\n\n      lang:Bash $ xvfb-run -a make test\n\n    instead of a plain make test. That'll automatically create a fake\n    xserver, set up DISPLAY and run make test in that environment.\n\n    That works well for manually installing modules. When installing us-\n    ing CPAN.pm you can make things easier by writing a distropref.\n\n    First, tell cpan where your distroprefs are. I use ~/.cpan/prefs:\n\n      lang:Bash $ cpan cpan[1]> o conf init prefs_dir [...] <prefs_dir>\n      Directory where to store default options/environment/dialogs for\n      building modules that need some customization? [] /home/rafl/.c-\n      pan/prefs cpan[3]> o conf commit commit: wrote '/home/rafl/.c-\n      pan/CPAN/MyConfig.pm'\n\n    Now write a distropref for the modules that need an X server and put\n    it into your prefs dir as X11.yml\n\n      ---\n      match: distribution: | /(?x:Wx |Gtk2 |Gnome2\n            |... other modules requiring an X server\n          )-\\d| test: commandline: \"xvfb-run -a make test\"\n\n    Now the tests for Wx, Gtk2, Gnome2 and all other distributions you\n    list in that regex will be executed with a fake X server.\n\n    I have yet to figure out how to write a distropref that just\n    prepends to the test commandline instead of replacing it so I won't\n    need to have another pref for all modules using Module::Build.\n"
title: Running tests that require an X server
type: pod
uri: http://perldition.org/articles/Running%20tests%20that%20require%20an%20X%20server.pod
xhtml: "<div class=\"pod\">\n<p>Lots of CPAN distributions require some kind of graphical\nenvironment. Some of them even pop up windows, which not only very\nannoying, but also sometimes fails if you're using a tiled window\nmanager.</p>\n<p>To test such distributions on a machine where no graphical environment\nis available or on your desktop while you're working and don't want to\nget annoyed to death you can use a fake X server, like Xvfb.</p>\n<p>The easiest way to do that is to run</p>\n<pre><span class=\"Normal\">$ xvfb-run -a </span><span class=\"BString\">make</span><span class=\"Normal\"> </span><span class=\"Reserved\">test</span>\n</pre>\n<p>instead of a plain <code>make test</code>. That'll automatically create a fake\nxserver, set up <code>DISPLAY</code> and run <code>make test</code> in that environment.</p>\n<p>That works well for manually installing modules. When installing using\n<code>CPAN.pm</code> you can make things easier by writing a distropref.</p>\n<p>First, tell cpan where your distroprefs are. I use <code>~/.cpan/prefs</code>:</p>\n<pre><span class=\"Normal\">$ cpan</span><span class=\"Normal\">\n</span><span class=\"Normal\">cpan[1]</span><span class=\"Operator\">&gt;</span><span class=\"Normal\"> o conf init prefs_dir</span><span class=\"Normal\">\n</span><span class=\"Normal\">[...]</span><span class=\"Normal\">\n</span><span class=\"Operator\">&lt;</span><span class=\"Normal\">prefs_dir</span><span class=\"Operator\">&gt;</span><span class=\"Normal\">\n</span><span class=\"Normal\">Directory where to store default options/environment/dialogs </span><span class=\"Keyword\">for</span><span class=\"Normal\">\n</span><span class=\"Normal\">building modules that need some customization? [] /home/rafl/.cpan/prefs</span><span class=\"Normal\">\n</span><span class=\"Normal\">cpan[3]</span><span class=\"Operator\">&gt;</span><span class=\"Normal\"> o conf commit</span><span class=\"Normal\">\n</span><span class=\"Normal\">commit: wrote </span><span class=\"String\">&apos;/home/rafl/.cpan/CPAN/MyConfig.pm&apos;</span>\n</pre>\n<p>Now write a distropref for the modules that need an X server and put\nit into your prefs dir as <code>X11.yml</code></p>\n<pre><span class=\"Normal\">---</span><span class=\"Normal\">\n</span><span class=\"Normal\">match:</span><span class=\"Normal\">\n</span><span class=\"Normal\">  distribution: </span><span class=\"Keyword\">|</span><span class=\"Normal\">\n</span><span class=\"Normal\">    /</span><span class=\"Keyword\">(</span><span class=\"Normal\">?x:Wx</span><span class=\"Normal\">\n</span><span class=\"Normal\">      </span><span class=\"Keyword\">|</span><span class=\"Normal\">Gtk2</span><span class=\"Normal\">\n</span><span class=\"Normal\">      </span><span class=\"Keyword\">|</span><span class=\"Normal\">Gnome2</span><span class=\"Normal\">\n</span><span class=\"Normal\">      </span><span class=\"Keyword\">|</span><span class=\"Normal\">..</span><span class=\"Keyword\">.</span><span class=\"Normal\"> other modules requiring an X server</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Keyword\">)</span><span class=\"Normal\">-\\d</span><span class=\"Keyword\">|</span><span class=\"Normal\">\n</span><span class=\"Normal\">test:</span><span class=\"Normal\">\n</span><span class=\"Normal\">  commandline: </span><span class=\"String\">&quot;xvfb-run -a make test&quot;</span>\n</pre>\n<p>Now the tests for Wx, Gtk2, Gnome2 and all other distributions you\nlist in that regex will be executed with a fake X server.</p>\n<p>I have yet to figure out how to write a distropref that just prepends\nto the test commandline instead of replacing it so I won't need to\nhave another pref for all modules using <code>Module::Build</code>.</p>\n\n\n</div>"
--- 
author: 
  email: rafl@fsfe.org
  keyid: 742f2a428e635a5e
  name: Florian Ragwitz
categories: 
  - Perl
date: 2009-04-28T06:09:31Z
guid: 97a76a6d-4019-4554-9993-2de23bde7e39
modified: 2009-04-28T06:20:16Z
raw: "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\n=pod\n\nFor quite some time perl provided a form of C<my> declarations that\nincludes a type name, like this:\n\n  lang:Perl\n  my Str $x = 'foo';\n\nHowever, that didn't do anything useful, until Vincent Pit came along\nand wrote the excellent\nL<Lexical::Types|http://search.cpan.org/perldoc?Lexical::Types>\nmodule, which allows you to extend the semantics of typed lexicals and\nactually make them do something useful. For that, it simply invokes a\ncallback for every C<my> declaration with a type in the scopes it is\nloaded. Within that callback you get the variable that is being\ndeclared as well as the name of the type used in the declaration.\n\nWe also have Moose type constraints and the great\nL<MooseX::Types|http://search.cpan.org/perldoc?MooseX::Types> module,\nthat allows us to define our own type libraries and import the type\nconstraints into other modules.\n\nLet's glue those modules together. Consider this code:\n\n  lang:Perl\n  use MooseX::Types::Moose qw/Int/;\n  use Lexical::Types;\n  my Int $x = 42;\n\nThe first problem is that the perl compiler expects a package with the\nname of the type used in C<my> to exist. If there's no such package\ncompilation will fail.\n\nCreating top-level namespaces for all the types we want to use would\nobviously suck. Luckily the compiler will also try to look for a\nfunction with the name of the type in the current scope. If that\nexists and is inlineable, it will call that function and use the\nreturn value as a package name.\n\nIn the above code snippet an C<Int> function already exists. We\nimported that from C<MooseX::Types::Moose>. Unfortunately it isn't\ninlineable. Even if it were, compilation would still fail, because it\nwould return a C<Moose::Meta::TypeConstraint> instead of a valid\npackage name.\n\nTo fix that, let's rewrite the code to this:\n\n  lang:Perl\n  use MooseX::Types::Moose qw/Int/;\n  use MooseX::Lexical::Types qw/Int/;\n  my Int $x = 42;\n\nLet's also write a MooseX::Lexical::Types module that replaces\nexisting imported type exports with something that can be inlined and\nreturns an existing package name based on the type constraint's name.\n\n  lang:Perl\n  package MooseX::Lexical::Types;\n\n  use Class::MOP;\n  use MooseX::Types::Util qw/has_available_type_export/;\n  use namespace::autoclean;\n\n  sub import {\n      my ($class, @args) = @_;\n      my $caller = caller();\n\n      my $meta = Class::MOP::class_of($caller) || Class::MOP::Class->initialize($caller);\n\n      for my $type_name (@args) {\n          # get the type constraint by introspecting the caller\n          my $type_constraint = has_available_type_export($caller, $type_name);\n\n          my $package = 'MooseX::Lexical::Types::TYPE::' . $type_constraint->name;\n          Class::MOP::Class->create($package);\n          $meta->add_package_symbol('&'.$type_name => sub () { $package });\n      }\n\n      Lexical::Types->import; # enable Lexical::Types for the caller\n  }\n\n  1;\n\nWith that the example code now compiles. Unfortunately it breaks every\nother usecase of MooseX::Types. The export will still need to return a\nC<Moose::Meta::TypeConstraint> at run time so this will continue to\nwork:\n\n  lang:Perl\n  has some_attribute => (is => 'ro', isa => Int);\n\nSo instead of returning a plain package name from our exported\nfunction we will return an object that delegates all method calls to\nthe actual type constraint, but evaluates to our special package name\nwhen used as a string:\n\n  lang:Perl\n  my $decorator = MooseX::Lexical::Types::TypeDecorator->new($type_constraint);\n  $meta->add_package_symbol('&'.$type_name => sub () { $decorator });\n\nand:\n\n  lang:Perl\n  package MooseX::Lexical::Types::TypeDecorator;\n  use Moose;\n  use namespace::autoclean;\n\n  # MooseX::Types happens to already have a class that doesn't do much\n  # more than delegating to a real type constraint!\n  extends 'MooseX::Types::TypeDecorator';\n\n  use overload '\"\"' => sub {\n      'MooseX::Lexical::Types::TYPE::' . $_[0]->__type_constraint->name\n  };\n\n  1;\n\nNow we're able to use C<Int> as usual and have Lexical::Types invoke\nits callback on C<MooseX::Lexical::Types::TYPE::Int>. Within that\ncallback we will need the real type constraint again, but as it is\ninvoked as a class method with no good way to pass in additional\narguments, we will need to store the type constraint somewhere. I\nchoose to simply add a method to the type class we create when\nconstructing our export. After that, all we need is to implement our\nLexical::Types callback. We will put that in a class all our type\nclasses will inherit from:\n\n  lang:Perl\n  Class::MOP::Class->create(\n      $package => (\n          superclasses => ['MooseX::Lexical::Types::TypedScalar'],\n          methods      => {\n              get_type_constraint => sub { $type_constraint },\n          },\n      ),\n  );\n\nThe Lexical::Types callback will now need to tie things together by\nmodifying the declared variable so it will automatically validate\nvalues against the type constraint when being assigned to. There are\nseveral ways of doing this. Using C<tie> on the declared variable\nwould probable be the easiest thing to do. However, I decided to use\nL<Variable::Magic|http://search.cpan.org/perldoc?Variable::Magic>\n(also written by Vincent Pit - did I mention he's awesome?), because\nit's mostly invisible at the perl level and also performs rather well\n(not that it'd matter, given that validation itself is relatively\nslow):\n\n  lang:Perl\n  package MooseX::Lexical::Types::TypedScalar;\n\n  use Carp qw/confess/;\n  use Variable::Magic qw/wizard cast/;\n  use namespace::autoclean;\n\n  my $wiz = wizard\n      # store the type constraint in the data attached to the magic\n      data => sub { $_[1]->get_type_constraint },\n      # when assigning to the variable, fail if we can't validate the\n      # new value ($_[0]) against the type constraint ($_[1])\n      set  => sub {\n          if (defined (my $msg = $_[1]->validate(${ $_[0] }))) {\n              confess $msg;\n          }\n          ();\n      };\n\n  sub TYPEDSCALAR {\n      # cast $wiz on the variable in $_[1]. pass the type package name\n      # in $_[0] to the wizard's data construction callback.\n      cast $_[1], $wiz, $_[0];\n      ();\n  }\n\n  1;\n\nWith this, our example code now works. If someone wants to assign,\nsay, C<'foo'> to the variable declared as C<my Int $x> our magic\ncallback will be invoked, try to validate the value against the type\nconstraint and fail loudly. B<WIN!>\n\nThe code for all this is available\nL<github|http://github.com/rafl/moosex-lexical-types> and should also\nbe on CPAN shortly.\n\nYou might notice warnings about mismatching prototypes. Those are\ncaused by Class::MOP and fixed in the git version of it, so they'll go\naway with the next release.\n\nThere's still a couple of caveats, but please see L<the\ndocumentation|http://search.cpan.org/perldoc?MooseX::Lexical::Types>\nfor that.\n\n=cut\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.6 (GNU/Linux)\n\niD8DBQFJ9qAgdC8qQo5jWl4RAni9AJoDwsG/8iNd2MlXvBLG6+1IOXCCnwCfZnys\nuUwBX0DArfYxN0EJf48Op2w=\n=xSW5\n-----END PGP SIGNATURE-----\n"
signed: 1
summary: " For quite some time perl provided a form of …"
tags: 
  - 
    perl: 0
  - 
    types: 0
  - 
    moose: 0
  - 
    syntax: 0
text: "    For quite some time perl provided a form of my declarations that in-\n    cludes a type name, like this:\n\n      lang:Perl my Str $x = 'foo';\n\n    However, that didn't do anything useful, until Vincent Pit came a-\n    long and wrote the excellent Lexical::Types module, which allows you\n    to extend the semantics of typed lexicals and actually make them do\n    something useful. For that, it simply invokes a callback for every\n    my declaration with a type in the scopes it is loaded. Within that\n    callback you get the variable that is being declared as well as the\n    name of the type used in the declaration.\n\n    We also have Moose type constraints and the great MooseX::Types mod-\n    ule, that allows us to define our own type libraries and import the\n    type constraints into other modules.\n\n    Let's glue those modules together. Consider this code:\n\n      lang:Perl use MooseX::Types::Moose qw/Int/; use Lexical::Types; my\n      Int $x = 42;\n\n    The first problem is that the perl compiler expects a package with\n    the name of the type used in my to exist. If there's no such package\n    compilation will fail.\n\n    Creating top-level namespaces for all the types we want to use would\n    obviously suck. Luckily the compiler will also try to look for a\n    function with the name of the type in the current scope. If that ex-\n    ists and is inlineable, it will call that function and use the re-\n    turn value as a package name.\n\n    In the above code snippet an Int function already exists. We im-\n    ported that from MooseX::Types::Moose. Unfortunately it isn't in-\n    lineable. Even if it were, compilation would still fail, because\n    it would return a Moose::Meta::TypeConstraint instead of a valid\n    package name.\n\n    To fix that, let's rewrite the code to this:\n\n      lang:Perl use MooseX::Types::Moose qw/Int/; use MooseX::Lexi-\n      cal::Types qw/Int/; my Int $x = 42;\n\n    Let's also write a MooseX::Lexical::Types module that replaces\n    existing imported type exports with something that can be in-\n    lined and returns an existing package name based on the type\n    constraint's name.\n\n      lang:Perl package MooseX::Lexical::Types;\n\n      use Class::MOP; use MooseX::Types::Util qw/has_available_type_ex-\n      port/; use namespace::autoclean;\n\n      sub import { my ($class, @args) = @_; my $caller = caller();\n\n          my $meta = Class::MOP::class_of($caller) ||\n          Class::MOP::Class->initialize($caller);\n\n          for my $type_name (@args) {\n              # get the type constraint by introspecting the caller\n              my $type_constraint = has_available_type_export($caller,\n              $type_name);\n\n              my $package = 'MooseX::Lexical::Types::TYPE::' . $type_-\n              constraint->name; Class::MOP::Class->create($package);\n              $meta->add_package_symbol('&'.$type_name => sub () { $-\n              package }); }\n\n          Lexical::Types->import; # enable Lexical::Types for the caller\n          }\n\n      1;\n\n    With that the example code now compiles. Unfortunately it breaks ev-\n    ery other usecase of MooseX::Types. The export will still need to\n    return a Moose::Meta::TypeConstraint at run time so this will con-\n    tinue to work:\n\n      lang:Perl has some_attribute => (is => 'ro', isa => Int);\n\n    So instead of returning a plain package name from our exported func-\n    tion we will return an object that delegates all method calls to the\n    actual type constraint, but evaluates to our special package name\n    when used as a string:\n\n      lang:Perl my $decorator = MooseX::Lexical::Types::TypeDecora-\n      tor->new($type_constraint); $meta->add_package_symbol('&'.$type_-\n      name => sub () { $decorator });\n\n    and:\n\n      lang:Perl package MooseX::Lexical::Types::TypeDecorator; use\n      Moose; use namespace::autoclean;\n\n      # MooseX::Types happens to already have a class that doesn't do\n      # much more than delegating to a real type constraint!\n      extends 'MooseX::Types::TypeDecorator';\n\n      use overload '\"\"' => sub { 'MooseX::Lexical::Types::TYPE::' .\n      $_[0]->__type_constraint->name };\n\n      1;\n\n    Now we're able to use Int as usual and have Lexical::Types invoke\n    its callback on MooseX::Lexical::Types::TYPE::Int. Within that call-\n    back we will need the real type constraint again, but as it is in-\n    voked as a class method with no good way to pass in additional argu-\n    ments, we will need to store the type constraint somewhere. I choose\n    to simply add a method to the type class we create when constructing\n    our export. After that, all we need is to implement our Lexi-\n    cal::Types callback. We will put that in a class all our type class-\n    es will inherit from:\n\n      lang:Perl Class::MOP::Class->create( $package => ( superclasses =>\n      ['MooseX::Lexical::Types::TypedScalar'], methods => { get_type_-\n      constraint => sub { $type_constraint }, }, ), );\n\n    The Lexical::Types callback will now need to tie things together by\n    modifying the declared variable so it will automatically validate\n    values against the type constraint when being assigned to. There are\n    several ways of doing this. Using tie on the declared variable would\n    probable be the easiest thing to do. However, I decided to use Vari-\n    able::Magic (also written by Vincent Pit - did I mention he's awe-\n    some?), because it's mostly invisible at the perl level and also\n    performs rather well (not that it'd matter, given that validation\n    itself is relatively slow):\n\n      lang:Perl package MooseX::Lexical::Types::TypedScalar;\n\n      use Carp qw/confess/; use Variable::Magic qw/wizard cast/; use\n      namespace::autoclean;\n\n      my $wiz = wizard\n          # store the type constraint in the data attached to the magic\n          data => sub { $_[1]->get_type_constraint },\n          # when assigning to the variable, fail if we can't validate\n          # the new value ($_[0]) against the type constraint ($_[1])\n          set => sub { if (defined (my $msg = $_[1]->validate(${ $_[0]\n          }))) { confess $msg; } (); };\n\n      sub TYPEDSCALAR {\n          # cast $wiz on the variable in $_[1]. pass the type package\n          # name in $_[0] to the wizard's data construction callback.\n          cast $_[1], $wiz, $_[0]; (); }\n\n      1;\n\n    With this, our example code now works. If someone wants to assign,\n    say, 'foo' to the variable declared as my Int $x our magic callback\n    will be invoked, try to validate the value against the type con-\n    straint and fail loudly. WIN!\n\n    The code for all this is available github and should also be on\n    CPAN shortly.\n\n    You might notice warnings about mismatching prototypes. Those are\n    caused by Class::MOP and fixed in the git version of it, so they'll\n    go away with the next release.\n\n    There's still a couple of caveats, but please see the documenta-\n    tion for that.\n"
title: Implementing Typed Lexical Variables
type: pod
uri: http://perldition.org/articles/Implementing%20Typed%20Lexical%20Variables.pod
xhtml: "<div class=\"pod\">\n<p>For quite some time perl provided a form of <code>my</code> declarations that\nincludes a type name, like this:</p>\n<pre><span class=\"Keyword\">my</span><span class=\"Normal\"> Str </span><span class=\"DataType\">$x</span><span class=\"Normal\"> = </span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">;</span>\n</pre>\n<p>However, that didn't do anything useful, until Vincent Pit came along\nand wrote the excellent\n<a href=\"http://search.cpan.org/perldoc?Lexical::Types\">Lexical::Types</a>\nmodule, which allows you to extend the semantics of typed lexicals and\nactually make them do something useful. For that, it simply invokes a\ncallback for every <code>my</code> declaration with a type in the scopes it is\nloaded. Within that callback you get the variable that is being\ndeclared as well as the name of the type used in the declaration.</p>\n<p>We also have Moose type constraints and the great\n<a href=\"http://search.cpan.org/perldoc?MooseX::Types\">MooseX::Types</a> module,\nthat allows us to define our own type libraries and import the type\nconstraints into other modules.</p>\n<p>Let's glue those modules together. Consider this code:</p>\n<pre><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Types</span><span class=\"Normal\">::</span><span class=\"Function\">Moose</span><span class=\"Normal\"> </span><span class=\"Operator\">qw/</span><span class=\"Normal\">Int</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">Lexical::Types</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"Function\">Int</span><span class=\"Normal\"> </span><span class=\"DataType\">$x</span><span class=\"Normal\"> = 42;</span>\n</pre>\n<p>The first problem is that the perl compiler expects a package with the\nname of the type used in <code>my</code> to exist. If there's no such package\ncompilation will fail.</p>\n<p>Creating top-level namespaces for all the types we want to use would\nobviously suck. Luckily the compiler will also try to look for a\nfunction with the name of the type in the current scope. If that\nexists and is inlineable, it will call that function and use the\nreturn value as a package name.</p>\n<p>In the above code snippet an <code>Int</code> function already exists. We\nimported that from <code>MooseX::Types::Moose</code>. Unfortunately it isn't\ninlineable. Even if it were, compilation would still fail, because it\nwould return a <code>Moose::Meta::TypeConstraint</code> instead of a valid\npackage name.</p>\n<p>To fix that, let's rewrite the code to this:</p>\n<pre><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Types</span><span class=\"Normal\">::</span><span class=\"Function\">Moose</span><span class=\"Normal\"> </span><span class=\"Operator\">qw/</span><span class=\"Normal\">Int</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Lexical</span><span class=\"Normal\">::</span><span class=\"Function\">Types</span><span class=\"Normal\"> </span><span class=\"Operator\">qw/</span><span class=\"Normal\">Int</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"Function\">Int</span><span class=\"Normal\"> </span><span class=\"DataType\">$x</span><span class=\"Normal\"> = 42;</span>\n</pre>\n<p>Let's also write a MooseX::Lexical::Types module that replaces\nexisting imported type exports with something that can be inlined and\nreturns an existing package name based on the type constraint's name.</p>\n<pre><span class=\"Keyword\">package</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Lexical</span><span class=\"Normal\">::</span><span class=\"Function\">Types</span><span class=\"Normal\">;</span>\n\n<span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">Class::MOP</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Types</span><span class=\"Normal\">::</span><span class=\"Function\">Util</span><span class=\"Normal\"> </span><span class=\"Operator\">qw/</span><span class=\"Normal\">has_available_type_export</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">namespace::autoclean</span><span class=\"Normal\">;</span>\n\n<span class=\"Keyword\">sub </span><span class=\"Function\">import</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Keyword\">my</span><span class=\"Normal\"> (</span><span class=\"DataType\">$class</span><span class=\"Normal\">, </span><span class=\"DataType\">@args</span><span class=\"Normal\">) = </span><span class=\"DataType\">@_</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$caller</span><span class=\"Normal\"> = </span><span class=\"Function\">caller</span><span class=\"Normal\">();</span>\n\n<span class=\"Normal\">    </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$meta</span><span class=\"Normal\"> = </span><span class=\"Function\">Class::MOP</span><span class=\"Normal\">::</span><span class=\"Function\">class_of</span><span class=\"Normal\">(</span><span class=\"DataType\">$</span><span class=\"Normal\">caller) || </span><span class=\"Function\">Class::MOP</span><span class=\"Normal\">::</span><span class=\"Function\">Class</span><span class=\"Normal\">-&gt;initialize(</span><span class=\"DataType\">$caller</span><span class=\"Normal\">);</span>\n\n<span class=\"Normal\">    </span><span class=\"Keyword\">for</span><span class=\"Normal\"> </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$type_name</span><span class=\"Normal\"> (</span><span class=\"DataType\">@args</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Comment\"># get the type constraint by introspecting the caller</span><span class=\"Comment\">\n</span><span class=\"Normal\">        </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$type_constraint</span><span class=\"Normal\"> = has_available_type_export(</span><span class=\"DataType\">$caller</span><span class=\"Normal\">, </span><span class=\"DataType\">$type_name</span><span class=\"Normal\">);</span>\n\n<span class=\"Normal\">        </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$package</span><span class=\"Normal\"> = </span><span class=\"Operator\">&apos;</span><span class=\"String\">MooseX::Lexical::Types::TYPE::</span><span class=\"Operator\">&apos;</span><span class=\"Normal\"> . </span><span class=\"DataType\">$type_constraint</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">name</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Function\">Class::MOP</span><span class=\"Normal\">::</span><span class=\"Function\">Class</span><span class=\"Normal\">-&gt;create(</span><span class=\"DataType\">$package</span><span class=\"Normal\">);</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"DataType\">$meta</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">add_package_symbol</span><span class=\"Normal\">(</span><span class=\"Operator\">&apos;</span><span class=\"String\">&amp;</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">.</span><span class=\"DataType\">$type_name</span><span class=\"Normal\"> =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">() { </span><span class=\"DataType\">$package</span><span class=\"Normal\"> });</span><span class=\"Normal\">\n</span><span class=\"Normal\">    }</span>\n\n<span class=\"Normal\">    </span><span class=\"Function\">Lexical::Types</span><span class=\"Normal\">-&gt;</span><span class=\"Function\">import</span><span class=\"Normal\">; </span><span class=\"Comment\"># enable Lexical::Types for the caller</span><span class=\"Comment\">\n</span><span class=\"Normal\">}</span>\n\n<span class=\"Float\">1</span><span class=\"Normal\">;</span>\n</pre>\n<p>With that the example code now compiles. Unfortunately it breaks every\nother usecase of MooseX::Types. The export will still need to return a\n<code>Moose::Meta::TypeConstraint</code> at run time so this will continue to\nwork:</p>\n<pre><span class=\"Normal\">has some_attribute =&gt; (is =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">ro</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, isa =&gt; </span><span class=\"Function\">Int</span><span class=\"Normal\">);</span>\n</pre>\n<p>So instead of returning a plain package name from our exported\nfunction we will return an object that delegates all method calls to\nthe actual type constraint, but evaluates to our special package name\nwhen used as a string:</p>\n<pre><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$decorator</span><span class=\"Normal\"> = </span><span class=\"Function\">MooseX::Lexical</span><span class=\"Normal\">::</span><span class=\"Function\">Types</span><span class=\"Normal\">::</span><span class=\"Function\">TypeDecorator</span><span class=\"Normal\">-&gt;new(</span><span class=\"DataType\">$type_constraint</span><span class=\"Normal\">);</span><span class=\"Normal\">\n</span><span class=\"DataType\">$meta</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">add_package_symbol</span><span class=\"Normal\">(</span><span class=\"Operator\">&apos;</span><span class=\"String\">&amp;</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">.</span><span class=\"DataType\">$type_name</span><span class=\"Normal\"> =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">() { </span><span class=\"DataType\">$decorator</span><span class=\"Normal\"> });</span>\n</pre>\n<p>and:</p>\n<pre><span class=\"Keyword\">package</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Lexical</span><span class=\"Normal\">::</span><span class=\"Function\">Types</span><span class=\"Normal\">::</span><span class=\"Function\">TypeDecorator</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> Moose;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">namespace::autoclean</span><span class=\"Normal\">;</span>\n\n<span class=\"Comment\"># MooseX::Types happens to already have a class that doesn&apos;t do much</span><span class=\"Comment\">\n</span><span class=\"Comment\"># more than delegating to a real type constraint!</span><span class=\"Comment\">\n</span><span class=\"Normal\">extends </span><span class=\"Operator\">&apos;</span><span class=\"String\">MooseX::Types::TypeDecorator</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">;</span>\n\n<span class=\"Keyword\">use</span><span class=\"Normal\"> overload </span><span class=\"Operator\">&apos;</span><span class=\"String\">&quot;&quot;</span><span class=\"Operator\">&apos;</span><span class=\"Normal\"> =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Operator\">&apos;</span><span class=\"String\">MooseX::Lexical::Types::TYPE::</span><span class=\"Operator\">&apos;</span><span class=\"Normal\"> . </span><span class=\"Variable\">$_</span><span class=\"Normal\">[0]</span><span class=\"Operator\">-</span><span class=\"Normal\">&gt;__type_constraint-&gt;name</span><span class=\"Normal\">\n</span><span class=\"Normal\">};</span>\n\n<span class=\"Float\">1</span><span class=\"Normal\">;</span>\n</pre>\n<p>Now we're able to use <code>Int</code> as usual and have Lexical::Types invoke\nits callback on <code>MooseX::Lexical::Types::TYPE::Int</code>. Within that\ncallback we will need the real type constraint again, but as it is\ninvoked as a class method with no good way to pass in additional\narguments, we will need to store the type constraint somewhere. I\nchoose to simply add a method to the type class we create when\nconstructing our export. After that, all we need is to implement our\nLexical::Types callback. We will put that in a class all our type\nclasses will inherit from:</p>\n<pre><span class=\"Function\">Class::MOP</span><span class=\"Normal\">::</span><span class=\"Function\">Class</span><span class=\"Normal\">-&gt;create(</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"DataType\">$package</span><span class=\"Normal\"> =&gt; (</span><span class=\"Normal\">\n</span><span class=\"Normal\">        superclasses =&gt; [</span><span class=\"Operator\">&apos;</span><span class=\"String\">MooseX::Lexical::Types::TypedScalar</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">],</span><span class=\"Normal\">\n</span><span class=\"Normal\">        methods      =&gt; {</span><span class=\"Normal\">\n</span><span class=\"Normal\">            get_type_constraint =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{ </span><span class=\"DataType\">$type_constraint</span><span class=\"Normal\"> },</span><span class=\"Normal\">\n</span><span class=\"Normal\">        },</span><span class=\"Normal\">\n</span><span class=\"Normal\">    ),</span><span class=\"Normal\">\n</span><span class=\"Normal\">);</span>\n</pre>\n<p>The Lexical::Types callback will now need to tie things together by\nmodifying the declared variable so it will automatically validate\nvalues against the type constraint when being assigned to. There are\nseveral ways of doing this. Using <code>tie</code> on the declared variable\nwould probable be the easiest thing to do. However, I decided to use\n<a href=\"http://search.cpan.org/perldoc?Variable::Magic\">Variable::Magic</a>\n(also written by Vincent Pit - did I mention he's awesome?), because\nit's mostly invisible at the perl level and also performs rather well\n(not that it'd matter, given that validation itself is relatively\nslow):</p>\n<pre><span class=\"Keyword\">package</span><span class=\"Normal\"> </span><span class=\"Function\">MooseX::Lexical</span><span class=\"Normal\">::</span><span class=\"Function\">Types</span><span class=\"Normal\">::</span><span class=\"Function\">TypedScalar</span><span class=\"Normal\">;</span>\n\n<span class=\"Keyword\">use</span><span class=\"Normal\"> Carp </span><span class=\"Operator\">qw/</span><span class=\"Normal\">confess</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">Variable::Magic</span><span class=\"Normal\"> </span><span class=\"Operator\">qw/</span><span class=\"Normal\">wizard cast</span><span class=\"Operator\">/</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Keyword\">use</span><span class=\"Normal\"> </span><span class=\"Function\">namespace::autoclean</span><span class=\"Normal\">;</span>\n\n<span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$wiz</span><span class=\"Normal\"> = wizard</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Comment\"># store the type constraint in the data attached to the magic</span><span class=\"Comment\">\n</span><span class=\"Normal\">    data =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{ </span><span class=\"Variable\">$_</span><span class=\"Normal\">[</span><span class=\"Float\">1</span><span class=\"Normal\">]</span><span class=\"Operator\">-</span><span class=\"Normal\">&gt;get_type_constraint },</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Comment\"># when assigning to the variable, fail if we can&apos;t validate the</span><span class=\"Comment\">\n</span><span class=\"Normal\">    </span><span class=\"Comment\"># new value ($_[0]) against the type constraint ($_[1])</span><span class=\"Comment\">\n</span><span class=\"Normal\">    set  =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Keyword\">if</span><span class=\"Normal\"> (</span><span class=\"Function\">defined</span><span class=\"Normal\"> (</span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$msg</span><span class=\"Normal\"> = </span><span class=\"Variable\">$_</span><span class=\"Normal\">[</span><span class=\"Float\">1</span><span class=\"Normal\">]</span><span class=\"Operator\">-</span><span class=\"Normal\">&gt;validate(</span><span class=\"DataType\">$</span><span class=\"Normal\">{ </span><span class=\"Variable\">$_</span><span class=\"Normal\">[0] }))) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">            confess </span><span class=\"DataType\">$msg</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Normal\">        }</span><span class=\"Normal\">\n</span><span class=\"Normal\">        ();</span><span class=\"Normal\">\n</span><span class=\"Normal\">    };</span>\n\n<span class=\"Keyword\">sub </span><span class=\"Function\">TYPEDSCALAR</span><span class=\"Normal\"> {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    </span><span class=\"Comment\"># cast $wiz on the variable in $_[1]. pass the type package name</span><span class=\"Comment\">\n</span><span class=\"Normal\">    </span><span class=\"Comment\"># in $_[0] to the wizard&apos;s data construction callback.</span><span class=\"Comment\">\n</span><span class=\"Normal\">    cast </span><span class=\"Variable\">$_</span><span class=\"Normal\">[</span><span class=\"Float\">1</span><span class=\"Normal\">], </span><span class=\"DataType\">$wiz</span><span class=\"Normal\">, </span><span class=\"Variable\">$_</span><span class=\"Normal\">[0];</span><span class=\"Normal\">\n</span><span class=\"Normal\">    ();</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n\n<span class=\"Float\">1</span><span class=\"Normal\">;</span>\n</pre>\n<p>With this, our example code now works. If someone wants to assign,\nsay, <code>'foo'</code> to the variable declared as <code>my Int $x</code> our magic\ncallback will be invoked, try to validate the value against the type\nconstraint and fail loudly. <strong>WIN!</strong></p>\n<p>The code for all this is available\n<a href=\"http://github.com/rafl/moosex-lexical-types\">github</a> and should also\nbe on CPAN shortly.</p>\n<p>You might notice warnings about mismatching prototypes. Those are\ncaused by Class::MOP and fixed in the git version of it, so they'll go\naway with the next release.</p>\n<p>There's still a couple of caveats, but please see <a href=\"http://search.cpan.org/perldoc?MooseX::Lexical::Types\">the documentation</a>\nfor that.</p>\n\n\n</div>"
--- 
author: 
  email: rafl@fsfe.org
  keyid: 742f2a428e635a5e
  name: Florian Ragwitz
categories: 
  - Perl
date: 2009-04-26T08:13:18Z
guid: c42e982b-d436-4680-b794-973c516befec
modified: 2009-04-26T09:14:50Z
raw: "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\n=pod\n\nFor a long time the L<Catalyst Framework|http://catalystframework.org> has been using code attributes\nto allow users to declare actions that certain URLs get dispatched to.\nThat looks something like this:\n\n  lang:Perl\n  sub base    : Chained('/')    PathPart('') CaptureArgs(0) { ... }\n  sub index   : Chained('base') PathPart('') Args(0)        { ... }\n  sub default : Chained('base') PathPart('') Args           { ... }\n\nIt's a nice and clean syntax that keeps all important information\nright next to the method it belongs to.\n\nHowever, attributes in perl have a couple of limitations. For one, the\ninterface the perl core provides to use them is horrible and doesn't\nprovide nearly enough information to do a lot of things, but most\nimportantly attributes are just plain strings. That means you will\nneed to parse something like C<\"Chained('base')\"> into\nC<< (Chained => 'base') >> yourself to make proper use of them.\n\nWhile that's easy for the above example, it can be very hard in the\ngeneral case because only perl can parse Perl. It's one of the reasons\nyou can't use L<Catalyst::Controller::ActionRole|http://search.cpan.org/perldoc?Catalyst::Controller::ActionRole> to apply\nparameterized roles to your action instances, because parsing\nparameters out of things like\nC<< Does(SomeRole => { names => [qw/affe tiger/], answer_re => qr/42/ }) >>\nwould be awful and wrong.\n\nWith Catalyst 5.8 most of the attribute related code has been removed\nfrom the internals. It's now using L<MooseX::MethodAttributes|http://search.cpan.org/perldoc?MooseX::MethodAttributes> to do\nall the heavy lifting. Also the internals of how actions are\nregistered have been refactored to make it easier to implement\nalternate ways without changing the Catalyst core.\n\nAs a proof of concept for this I implemented a new way of declaring\nactions that's very similar to how L<Moose|http://search.cpan.org/perldoc?Moose> provides it's sugar\nfunctions. You can get it from\nL<github|http://github.com/rafl/catalystx-actions/tree>.\n\nWith that, the above example looks like this:\n\n  lang:Perl\n  action base    => (Chained => '/',    PathPart => '', CaptureArgs => 0) => sub { ... };\n  action index   => (Chained => 'base', PathPart => '', Args    => 0    ) => sub { ... };\n  action default => (Chained => 'base', PathPart => '', Args    => undef) => sub { ... };\n\n\nIt also moves method declaration from compiletime to runtime, making\nthis possible:\n\n  lang:Perl\n  for my $action (qw/foo bar baz/) {\n      action $action => (Chained => 'somewhere', Args => 0) => sub {\n          my ($self, $ctx) = @_;\n          $ctx->stash->{ $action } = $ctx->model('Foo')->get_stuff($action);\n      };\n  }\n\nAdmittedly, that's all very ugly, but illustrates well what kind of\nthings we're able to do now. But it doesn't need to be ugly. With\nL<Devel::Declare|http://search.cpan.org/perldoc?Devel::Declare> we have a great tool to add our own awesome syntax\nto perl, similar to how things like L<MooseX::Method::Signatures|http://search.cpan.org/perldoc?MooseX::Method::Signatures>,\nL<MooseX::MultiMethods|http://search.cpan.org/perldoc?MooseX::MultiMethods> and L<MooseX::Declare|http://search.cpan.org/perldoc?MooseX::Declare> do.\n\nSo how would a declarative syntax for Catalyst controllers look like?\nI don't know. Ideas include something like this:\n\n  under /some/where, action foo ('foo', $id) { ... }\n\nto mean:\n\n  sub foo : Chained('/some/where') PathPart('foo') CaptureArgs(1) { ... }\n\nAdding Moose type constraints to this would be interesting, too, and\nmake validation of captures and arguments a lot easier. Multi dispatch\nsimilar to MooseX::MultiMethods could be handy as well:\n\n  under /some/where {\n      action ('foo', Int $id) {\n          # find and stash an item by id\n      }\n      action ('foo', Str $name) {\n          # search items using $name\n      }\n      action ('foo', Any $thing) {\n          # display error page\n      }\n  }\n\nSo you see there are a lot of possibilities that should be\nexplored. Unfortunately I have no idea what kind of syntax and\nfeatures people would like to have, so your feedback on this would be\nmuch appreciated. :-)\n\n=cut\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.6 (GNU/Linux)\n\niD8DBQFJ9CYKdC8qQo5jWl4RAsRKAJ9Yad61aq7PRrSOiSV4+uFOWQuLRQCeKtwG\n0UpKH9fhZnP//tWX66Ispf0=\n=Lray\n-----END PGP SIGNATURE-----\n"
signed: 1
summary: " For a long time the Catalyst Framework has been …"
tags: 
  - 
    perl: 0
  - 
    syntax: 0
  - 
    catalyst: 0
text: "    For a long time the Catalyst Framework has been using code at-\n    tributes to allow users to declare actions that certain URLs get\n    dispatched to. That looks something like this:\n\n      lang:Perl sub base : Chained('/') PathPart('') CaptureArgs(0) {\n      ... } sub index : Chained('base') PathPart('') Args(0) { ... } sub\n      default : Chained('base') PathPart('') Args { ... }\n\n    It's a nice and clean syntax that keeps all important information\n    right next to the method it belongs to.\n\n    However, attributes in perl have a couple of limitations. For one,\n    the interface the perl core provides to use them is horrible and\n    doesn't provide nearly enough information to do a lot of things, but\n    most importantly attributes are just plain strings. That means you\n    will need to parse something like \"Chained('base')\" into (Chained =>\n    'base') yourself to make proper use of them.\n\n    While that's easy for the above example, it can be very hard in the\n    general case because only perl can parse Perl. It's one of the rea-\n    sons you can't use Catalyst::Controller::ActionRole to apply parame-\n    terized roles to your action instances, because parsing parameters\n    out of things like Does(SomeRole => { names => [qw/affe tiger/], an-\n    swer_re => qr/42/ }) would be awful and wrong.\n\n    With Catalyst 5.8 most of the attribute related code has been re-\n    moved from the internals. It's now using MooseX::MethodAttributes to\n    do all the heavy lifting. Also the internals of how actions are reg-\n    istered have been refactored to make it easier to implement alter-\n    nate ways without changing the Catalyst core.\n\n    As a proof of concept for this I implemented a new way of declaring\n    actions that's very similar to how Moose provides it's sugar func-\n    tions. You can get it from github.\n\n    With that, the above example looks like this:\n\n      lang:Perl action base => (Chained => '/', PathPart => '', Cap-\n      tureArgs => 0) => sub { ... }; action index => (Chained => 'base',\n      PathPart => '', Args => 0 ) => sub { ... }; action default =>\n      (Chained => 'base', PathPart => '', Args => undef) => sub { ... };\n\n    It also moves method declaration from compiletime to runtime, making\n    this possible:\n\n      lang:Perl for my $action (qw/foo bar baz/) { action $action =>\n      (Chained => 'somewhere', Args => 0) => sub { my ($self, $ctx) =\n      @_; $ctx->stash->{ $action } = $ctx->model('Foo')->get_stuff($ac-\n      tion); }; }\n\n    Admittedly, that's all very ugly, but illustrates well what kind of\n    things we're able to do now. But it doesn't need to be ugly. With\n    Devel::Declare we have a great tool to add our own awesome syntax to\n    perl, similar to how things like MooseX::Method::Signatures,\n    MooseX::MultiMethods and MooseX::Declare do.\n\n    So how would a declarative syntax for Catalyst controllers look\n    like? I don't know. Ideas include something like this:\n\n      under /some/where, action foo ('foo', $id) { ... }\n\n    to mean:\n\n      sub foo : Chained('/some/where') PathPart('foo') Cap-\n      tureArgs(1) { ... }\n\n    Adding Moose type constraints to this would be interesting, too, and\n    make validation of captures and arguments a lot easier. Multi dis-\n    patch similar to MooseX::MultiMethods could be handy as well:\n\n      under /some/where { action ('foo', Int $id) {\n              # find and stash an item by id\n          } action ('foo', Str $name) {\n              # search items using $name\n          } action ('foo', Any $thing) {\n              # display error page\n          } }\n\n    So you see there are a lot of possibilities that should be ex-\n    plored. Unfortunately I have no idea what kind of syntax and fea-\n    tures people would like to have, so your feedback on this would be\n    much appreciated.\n    :-)\n"
title: Declaring Catalyst Actions
type: pod
uri: http://perldition.org/articles/Declaring%20Catalyst%20Actions.pod
xhtml: "<div class=\"pod\">\n<p>For a long time the <a href=\"http://catalystframework.org\">Catalyst Framework</a> has been using code attributes\nto allow users to declare actions that certain URLs get dispatched to.\nThat looks something like this:</p>\n<pre><span class=\"Keyword\">sub </span><span class=\"Function\">base</span><span class=\"Normal\">    : Chained(</span><span class=\"Operator\">&apos;</span><span class=\"String\">/</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">)    PathPart(</span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">) CaptureArgs(0) { ... }</span><span class=\"Normal\">\n</span><span class=\"Keyword\">sub </span><span class=\"Function\">index</span><span class=\"Normal\">   : Chained(</span><span class=\"Operator\">&apos;</span><span class=\"String\">base</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">) PathPart(</span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">) Args(0)        { ... }</span><span class=\"Normal\">\n</span><span class=\"Keyword\">sub </span><span class=\"Function\">default</span><span class=\"Normal\"> : Chained(</span><span class=\"Operator\">&apos;</span><span class=\"String\">base</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">) PathPart(</span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">) Args           { ... }</span>\n</pre>\n<p>It's a nice and clean syntax that keeps all important information\nright next to the method it belongs to.</p>\n<p>However, attributes in perl have a couple of limitations. For one, the\ninterface the perl core provides to use them is horrible and doesn't\nprovide nearly enough information to do a lot of things, but most\nimportantly attributes are just plain strings. That means you will\nneed to parse something like <code>&quot;Chained('base')&quot;</code> into\n<code>(Chained =&gt; 'base')</code> yourself to make proper use of them.</p>\n<p>While that's easy for the above example, it can be very hard in the\ngeneral case because only perl can parse Perl. It's one of the reasons\nyou can't use <a href=\"http://search.cpan.org/perldoc?Catalyst::Controller::ActionRole\">Catalyst::Controller::ActionRole</a> to apply\nparameterized roles to your action instances, because parsing\nparameters out of things like\n<code>Does(SomeRole =&gt; { names =&gt; [qw/affe tiger/], answer_re =&gt; qr/42/ })</code>\nwould be awful and wrong.</p>\n<p>With Catalyst 5.8 most of the attribute related code has been removed\nfrom the internals. It's now using <a href=\"http://search.cpan.org/perldoc?MooseX::MethodAttributes\">MooseX::MethodAttributes</a> to do\nall the heavy lifting. Also the internals of how actions are\nregistered have been refactored to make it easier to implement\nalternate ways without changing the Catalyst core.</p>\n<p>As a proof of concept for this I implemented a new way of declaring\nactions that's very similar to how <a href=\"http://search.cpan.org/perldoc?Moose\">Moose</a> provides it's sugar\nfunctions. You can get it from\n<a href=\"http://github.com/rafl/catalystx-actions/tree\">github</a>.</p>\n<p>With that, the above example looks like this:</p>\n<pre><span class=\"Normal\">action base    =&gt; (Chained =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">/</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">,    PathPart =&gt; </span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">, CaptureArgs =&gt; 0) =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{ ... };</span><span class=\"Normal\">\n</span><span class=\"Normal\">action </span><span class=\"Function\">index</span><span class=\"Normal\">   =&gt; (Chained =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">base</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, PathPart =&gt; </span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">, Args    =&gt; 0    ) =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{ ... };</span><span class=\"Normal\">\n</span><span class=\"Normal\">action default =&gt; (Chained =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">base</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, PathPart =&gt; </span><span class=\"Operator\">&apos;&apos;</span><span class=\"Normal\">, Args    =&gt; </span><span class=\"Function\">undef</span><span class=\"Normal\">) =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{ ... };</span>\n\n\n</pre>\n<p>It also moves method declaration from compiletime to runtime, making\nthis possible:</p>\n<pre><span class=\"Keyword\">for</span><span class=\"Normal\"> </span><span class=\"Keyword\">my</span><span class=\"Normal\"> </span><span class=\"DataType\">$action</span><span class=\"Normal\"> (</span><span class=\"Operator\">qw/</span><span class=\"Normal\">foo bar baz</span><span class=\"Operator\">/</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    action </span><span class=\"DataType\">$action</span><span class=\"Normal\"> =&gt; (Chained =&gt; </span><span class=\"Operator\">&apos;</span><span class=\"String\">somewhere</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, Args =&gt; 0) =&gt; </span><span class=\"Keyword\">sub </span><span class=\"Normal\">{</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Keyword\">my</span><span class=\"Normal\"> (</span><span class=\"DataType\">$self</span><span class=\"Normal\">, </span><span class=\"DataType\">$ctx</span><span class=\"Normal\">) = </span><span class=\"DataType\">@_</span><span class=\"Normal\">;</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"DataType\">$ctx</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">stash</span><span class=\"Normal\">-&gt;{ </span><span class=\"DataType\">$action</span><span class=\"Normal\"> } = </span><span class=\"DataType\">$ctx</span><span class=\"Normal\">-&gt;</span><span class=\"DataType\">model</span><span class=\"Normal\">(</span><span class=\"Operator\">&apos;</span><span class=\"String\">Foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">)</span><span class=\"Operator\">-</span><span class=\"Normal\">&gt;get_stuff(</span><span class=\"DataType\">$action</span><span class=\"Normal\">);</span><span class=\"Normal\">\n</span><span class=\"Normal\">    };</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n</pre>\n<p>Admittedly, that's all very ugly, but illustrates well what kind of\nthings we're able to do now. But it doesn't need to be ugly. With\n<a href=\"http://search.cpan.org/perldoc?Devel::Declare\">Devel::Declare</a> we have a great tool to add our own awesome syntax\nto perl, similar to how things like <a href=\"http://search.cpan.org/perldoc?MooseX::Method::Signatures\">MooseX::Method::Signatures</a>,\n<a href=\"http://search.cpan.org/perldoc?MooseX::MultiMethods\">MooseX::MultiMethods</a> and <a href=\"http://search.cpan.org/perldoc?MooseX::Declare\">MooseX::Declare</a> do.</p>\n<p>So how would a declarative syntax for Catalyst controllers look like?\nI don't know. Ideas include something like this:</p>\n<pre><span class=\"Normal\">under /some/where, action foo (</span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, </span><span class=\"DataType\">$id</span><span class=\"Normal\">) { ... }</span>\n</pre>\n<p>to mean:</p>\n<pre><span class=\"Keyword\">sub </span><span class=\"Function\">foo</span><span class=\"Normal\"> : Chained(</span><span class=\"Operator\">&apos;</span><span class=\"String\">/some/where</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">) PathPart(</span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">) CaptureArgs(</span><span class=\"Float\">1</span><span class=\"Normal\">) { ... }</span>\n</pre>\n<p>Adding Moose type constraints to this would be interesting, too, and\nmake validation of captures and arguments a lot easier. Multi dispatch\nsimilar to MooseX::MultiMethods could be handy as well:</p>\n<pre><span class=\"Normal\">under /some/where {</span><span class=\"Normal\">\n</span><span class=\"Normal\">    action (</span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, </span><span class=\"Function\">Int</span><span class=\"Normal\"> </span><span class=\"DataType\">$id</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Comment\"># find and stash an item by id</span><span class=\"Comment\">\n</span><span class=\"Normal\">    }</span><span class=\"Normal\">\n</span><span class=\"Normal\">    action (</span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, Str </span><span class=\"DataType\">$name</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Comment\"># search items using $name</span><span class=\"Comment\">\n</span><span class=\"Normal\">    }</span><span class=\"Normal\">\n</span><span class=\"Normal\">    action (</span><span class=\"Operator\">&apos;</span><span class=\"String\">foo</span><span class=\"Operator\">&apos;</span><span class=\"Normal\">, Any </span><span class=\"DataType\">$thing</span><span class=\"Normal\">) {</span><span class=\"Normal\">\n</span><span class=\"Normal\">        </span><span class=\"Comment\"># display error page</span><span class=\"Comment\">\n</span><span class=\"Normal\">    }</span><span class=\"Normal\">\n</span><span class=\"Normal\">}</span>\n</pre>\n<p>So you see there are a lot of possibilities that should be\nexplored. Unfortunately I have no idea what kind of syntax and\nfeatures people would like to have, so your feedback on this would be\nmuch appreciated. :-)</p>\n\n\n</div>"
