3 ms·
Perl6 also has a macro keyword for creating hygienic macros - http://en.wikipedia.org/wiki/Perl_6#Macros http://en.wikipedia.org/wiki/Perl_6#Macros For Perl5
by draegtun 14y ago
Perl6 also has a macro keyword for creating hygienic macros - http://en.wikipedia.org/wiki/Perl_6#Macros http://en.wikipedia.org/wiki/Perl_6#Macros
For Perl5 you can use Devel::Declare (https://metacpan.org/module/Devel::Declare https://metacpan.org/module/Devel::Declare) or Devel::CallParser (https://metacpan.org/module/Devel::CallParser https://metacpan.org/module/Devel::CallParser) to achieve macro like effects.
For eg. Here's the Sweet.js def add macro using Devel::Declare...
package MyDef;
use strict;
use warnings;
use base 'Devel::Declare::MethodInstaller::Simple';
sub import {
my $class = shift;
my $caller = caller;
my $arg = shift;
$class->install_methodhandler(
into => $caller,
name => 'def',
);
}
sub parse_proto {
my $ctx = shift;
my ($proto) = @_;
"my ($proto) = \@_;";
}
1;
Then...
use 5.016;
use warnings;
use MyDef;
def add ($x, $y) { $x + $y }
say add(1, 2); # => 3
So when the compiler sees the def keyword then MyDef takes over and converts the line into...
sub add { my ($x, $y) = @_; $x + $y }
... then passes everything back to the perl parser to continue compiling the rest of the code.