> macro foo($a,$b) {
>       return( $c // $a+$b );
> }
>
> print foo(1,2), "\n";
> my $c=100;
> print foo(1,2) "\n";

Yeah, your example provided is correct. It's called variable
capture, and there's some work required by common lisp macros to
ensure that unwanted variable capture does not occur.

> I don't know. It doesn't seem to me like there's a benefit here that
> inline functions don't get you, AND you want programmers to ever use. Am
> I missing something?

Well, at first glance variable capture looks really bad. And it is, where
it's not intended. But used properly, it's another valuable tool in your
toolkit. For example:

Common lisp defines its for loops, while loops, etc using macros, for
example:
macro forintlist( ( $var, $bot, $top) $code ) {
  return <<"EOF";
  for my $var (($bot)..($top)) {
    $code
  }
EOF
}

And can be called with:
forintlist( ($a, 1=>10) {
  print "$a\n";
}); #note, the code block passed to while does not get evaluated on the
call to while, since $a shouldn't be bound here, but rather later, when
it's interpolated.

An example of where variable capture is needed is:
macro println ($a) {
  return <<"EOF";
  print $a;
  print "\n";
EOF
}
for my $b (1..100) {
  println $b;
}

Personally, I'm at a loss for how macros will fit seamlessly in Perl 6.
The examples above return a string, instead of real code (to make it
easier to see how the interpolation works.) The code passes in a block of
code, which magically gets interpolated back into a string as its original
code form.

Other things which the above 'forintlist' example used was the ability to
send an arbitrary structure to the macro, and have it be matched against
the parameter list for the macro. This allows one more flexibility in
passing parameters to a macro, as they don't need to be a straight out
list/array, but can be more complicatged structures, which are
automagically matched. If this were in perl 6, regular array/list argument
passing could be a simple case of a more complex argument/parameter
passing structure.

All of these things would probably be too complex to implement in Perl 6,
despite their power...they'd have some semantic mismatches with what makes
Perl perl. But I love lisp's power, and just hate its syntax. If I could
combine a 'real languages' syntax with the expressiveness of Perl, I'd be
quite the happy camper. And that's all I'm trying to do here.

Thanks,
Mike Lambert


Reply via email to