Catalyst is easy – less scary interlude
Posted by brunorc on June 10, 2009
Last time I was showing the famous, dreadfully obfuscated Perl code. It even included the horribly cryptic $_ variable! Now the code should look like this:
sub index :Path :Args(0) {
my ( $self, $c ) = @_;
my $list = join( "\n",
map { "<li>$_</li>" }
qw/beer bacon pierogi/ );
$c->response->body( <<END );
<html>
<head>
<title>My items</title>
</head>
<body>
<ul>
$list
</ul>
</body>
</html>
END
}
The <<END tells Perl print everything until you reach the line starting with END. This technique is known as “here doc”. But Perl prints even more, since there is no “$list” printed – instead the variable is interpolated, which means the content of the variable will be seen. The same would happen if the here doc was written like <<"END".
But what if we wanted to print the string “$list”? We could escape the $ sign, using backslash: \$list. Otherwise we could use single quotes, writing <<'END'. In this mode everything would be printed ‘as-is’. If we wanted to mix variables with actual $ signs we should use double quotes and escaping, since there’s no tricky escape which would cause the variable to be interpolated inside single quotes (at least I don’t know it).
With this knowledge and qq operator the code can be transformed into something more clean:
sub index :Path :Args(0) {
my ( $self, $c ) = @_;
my @items = ( 'beer', 'bacon', 'pierogi' );
my $list = '';
foreach my $item ( @items ) {
$list .= "<li>$item</li>\n";
}
my $template = qq[
<html>
<head>
<title>My items</title>
</head>
<body>
<ul>
$list
</ul>
<p>Only \$5!</p>
</body>
</html>
];
$c->response->body( $template );
}
The qq operator with its delimiters works exactly the same way as a pair of double quotes (can you imagine how the q[] operator would work?).
Now the code has two parts: lines 4-9 prepare the data, while lines 11-23 take care of presentation. Such separation of concerns can be quite useful and is often called Model-View-Controller (MVC). And although Catalyst is very MVC oriented, it allows one to decide by oneself how much separation should be used.
