In his last post, Dennis Ferron comments on _why's web server yown written in Io. One thing he comments is the slot 'forward'.
As he says, forward is a kind of catch that gets called when a message has been sent to an object and that object didn't have a selector with that name. _why exploits this feature to write an html builder based on that.
What he doesn't mention (I think he's leaving this for another post) is about lazyness. The way _why wrote forward method.
If you define a method without arguments but you call it with some, you can still access them, but with the difference that they won't be evaluated by default. That's called lazyness, and allows you to define the evaluation order of things.
So in the code
html(
title("O HAI")
strong("KTHXBYE")
)
forward will trap html message before title or strong.
In Perl, there's a 'lightning rod' function too, called AUTOLOAD. You can do pretty much the same, but the difference is that perl will ALWAYS evaluate parameters sent to a function before calling it, so the same code would trigger AUTOLOAD on the 'title' call, then 'strong', and last, 'html' and you have to fill the string from the inner tag to the most generic one.
Here's a gist code that emulates Yown Builder.io in Perl 5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Data::Dumper::Perltidy; | |
use Getopt::Long; | |
use Perl6::Say; | |
use Pod::Usage; | |
use autodie; | |
use strict; | |
use warnings; | |
our $AUTOLOAD; | |
sub man {#{{{ | |
pod2usage( | |
-exitval => 1, | |
-verbose => 2 | |
); | |
}#}}} | |
# main | |
GetOptions ( | |
'man' => \&man, | |
); | |
sub AUTOLOAD { | |
$AUTOLOAD=~ /.*::(.*)$/; | |
my $fill=''; | |
my @a = split(/_/,$1); | |
if (1<@a) { | |
$fill=" class='$a[1]'"; | |
} | |
return "<$a[0]$fill>\n@_\n</$a[0]>\n"; | |
} | |
say hola( | |
adeu_thisismyclass("hola"), | |
ital() | |
); | |
__END__#{{{ | |
=head1 NAME | |
AutoBuild | |
=head1 SEE ALSO | |
=head1 SYNOPSIS | |
say hola( | |
adeu_thisismyclass("hola"), | |
ital() | |
) | |
outputs | |
<hola > | |
<adeu class='thisismyclass'> | |
hola | |
</adeu> | |
<ital > | |
</ital> | |
</hola> | |
=head1 DESCRIPTION | |
Tiny DSL to dinamically build html-like text based on AUTOLOAD Perl5 feature | |
=head1 AUTHOR | |
Raimon Grau Cuscó <raimonster@gmail.com> | |
=head1 Credits | |
=cut | |
# vim: set tabstop=4 shiftwidth=4 foldmethod=marker : ###}}} |
Good luck Dennis with your new blog!
--
raig