Perl parameter passing

Jesse set me a challenge: make Perl 6-style parameter handling work in Perl 5. Without source filters. This is hard. But not, as was earlier claimed, impossible. When people say things are impossible with Perl, it just makes me want to go on and do them.

I've done this proof of concept:

package foo;
use Method;
sub new { bless {} }
sub bar :method { print $self; }
foo->new->bar();

The way it works is: all marked subroutines are scanned, and a pad (my) variable $self is allocated if there isn't one already. Then all references to $self the global - as in the method above - are converted into references to the lexical variable. Then - and this is the horrific bit - a bunch of Perl ops are injected into the code stream at the beginning of the method, like so:

    OP* padop = newOP(OP_PADSV, 0);
    OP* assignop =
        newASSIGNOP(OPf_STACKED,
            padop,
            0,
            newUNOP(OP_SHIFT, 0,
                newAVREF(newGVOP(OP_GV, 0, PL_defgv))
            )
        );
    OP* startop = Perl_linklist(aTHX_ assignop);
    padop->op_targ = offset;
    assignop->op_next = op->op_next;
    op->op_next = startop;

From there to full-blown Perl 6 parameter parsing is a simple matter of programming...


Full version - 0 Comments