Bailamos
Posted: 10/01/2011 Filed under: Perl 2 CommentsSince spanish classes (I mean the classes at the University, not the type definitions, you wierdo) aren’t as exciting as I would like them to be, my thoughts have wondered a bit further. Yeah, Perl 6 again. The idea isn’t new, but the point of showing off the intersting things it always fresh. So, ladies and gents, here’s a minimal part of Dancer implemented in Perl 6! To give some justice to my spanish classes, it’s not named Dancer, or even MiniDancer.
module Bailador;
use HTTP::Server::Simple::PSGI;
my @routes;
multi get(Pair $x) is export {
@routes.push: $x;
}
sub dispatch($env) {
for @routes -> $r {
if $env ~~ $r.key {
if $/ {
return $r.value.(|$/.list);
} else {
return $r.value.();
}
}
}
return "404";
}
sub bailar is export {
my $app = sub ($env) {
my $res = dispatch($env);
return ['200', [ 'Content-Type' => 'text/plain' ], $res];
}
given HTTP::Server::Simple::PSGI.new {
.host = 'localhost';
.app($app);
.run;
}
}
Although simple and stupid, it works. Let’s see some example application:
use Bailador;
# simple cases
get '/' => sub {
"hello world"
};
get '/about' => sub {
"about me"
};
# regexes, as usual
get /foo(.+)/ => sub ($x) {
"regexes! I got $x"
}
get / '/' (.+) '-' (.+)/ => sub ($x, $y) {
"$x and $y"
}
# junctions work too
get any('/h', '/help', '/halp') => sub {
"junctions are cool"
}
bailar;
The glory of smartmatching gives as the ability to use the get() sub with regexes and junctions (and almost everything else in Perl 6 to be honest) without even thinking about it.
Now where’s named parameters, where are the other HTTP methods? Well, that is left as an excercise for the reader. I hope you’re inspired enough :)
Very succinct! I have implemented similar dispatchers in Perl 5, but it looks much cleaner using some of the newer Perl 6 features.
I am curious what the pipe in ‘$r.value.(|$/.list);’ does.
Short anwer: it makes a list become an argument list for a subroutine.
You can find a longer answer in the specification: http://perlcabal.org/syn/S06.html#Flattening_argument_lists