[% setvar title Immediate subroutines %]
To see what is currently happening visit http://www.perl6.org/
Immediate subroutines
Maintainer: Jean-Louis Leroy Date: 4 Aug 2000 Last Modified: 1 Oct 2000 Mailing List: perl6-language@perl.org Number: 18 Version: 2 Status: Frozen
This very simple construct, inspired by the Forth language, makes the parser extensible by Perl code, providing powerful macro capabilities, multi-line comments, inline functions and conditional compilation.
CHANGES
Made code examples start at column 4 for proper HTML rendering.
When the parser sees a subroutine that has been marked as 'immediate', it calls it immediately. The call's arguments are implicitly quoted as with q{} and the resulting strings are passed to the subroutine. The entire call is removed from the parse stream and replaced with the subroutine's return value.
use immediate qw( compileif ); # mark subroutines as immediate
# multiline comments
sub comment
{
return '';
}
use immediate 'comment';
sub foo
{
# ...
comment {
this is a multiline comment;
the call to comment is executed at parse time
and returns an empty string that replaces
the whole call in the parse stream };
}
# conditional compilation
sub compileif
{
my ($condition, $body) = @_;
return eval($condition) ? $body : '';
}
use immediate qw( compileif ); # mark subroutines as immediate
sub bar
{
compileif -e 'state'
{
do 'state';
}
compileif $Module::VERSION > 1.23,
{
# blah blah blah
}
}
# macros
sub square
{
my $arg = shift;
my $gensym = $arg . '_';
$gensym .= '_' while $arg =~ /$gensym/;
return "do { $gensym = $arg; $gensym * $gensym }";
}
A flag is associated with the data structure associated to a subroutine by the parser. The pragmatic module 'immediate' is used to turn the flag on. When the parser recognizes a subroutine call, it checks the flag and if it's true, proceeds as described above.
The Forth standard.
"Starting Forth", by Leo Brodie