On Wed, 2002-03-27 at 11:31, Dan Sugalski wrote:
> At 10:27 AM -0500 3/27/02, Aaron Sherman wrote:

> >     macro mygrep ($code is macroblock, *@list) {
> >       my @newlist = ();
> >       for @list {
> >         push @newlist, $_ if $code.();
> >       }
> >       return @newlist;
> >     }
> >     @x = mygrep {/\S/} $fh.getlines();

This just brought something to mind when I re-read it. I was thinking
about how this would transform back into Perl, and I thought... gee, you
can't do that easily because you're taking the result of a block, and
Perl can only do that via function call or eval, both of which have
overhead that I hope we're not implying.

GNU C solves this problem in C by introducing the extension, "({})" like
so:

    #define swapout(a,b,new) ({typeof(a) tmp=a;a=b;b=new;tmp;})
    old1 = swapout(var1,var2,rand(100));

Which, behaves suspiciously like Perl and (which got this behavior from
LISP) ;) The value of the last statement in the block would be the
return value of the EXPRESSION (it's not a statement).

So, this concept (if not the syntax) would help us in Perl, because the
above statement would macro-expand to:

    @x = ({
        my @list = ({$fh.getlines()});
        my @newlist;
        for @list {
                push @newlist, $_ if ({/\S/});
        }
        return @newlist;
    });

This is not a great example because /\S/ is a valid expression, but if
we called it with something more complex, you would need this to expand
the macro. Perl will never have to do this, as it'll all be syntax tree
internally, but it would be nice to be able to expand byte code back out
to Perl without introducing extra overhead.

In this sense, I see Perl's ({}) as being exactly the same as eval{} (or
whatever the Perl6 version is), but without the exception trapping.

The only problem is that in Perl, ({}) is already valid syntax (paren
grouping around an anonymous hash). So, you might need to special case
it, or come up with a different syntax (expr{} perhaps).

> Just out of curiosity, is there anything macros (in the Lisp sense) 
> can do that source filters can't?

By definition, no. However, it would be harder for your source filter to
deal with the language correctly. It's difficult in C. In Perl it might
be impossible to get it right a majority of the time.



Reply via email to