root am Freitag, 6. Januar 2006 13.15:
> Hello,
> about closure I read the
>
> Perl literacy course
>
> lecture #9 Closures
>
> Shlomo Yona http://cs.haifa.ac.il/~shlomo/
>
>
> The explanations are clear but in this example:
> (it's an excerpt of an example of Shlomo)
>
> #!/usr/bin/perl
> use warnings;
> use strict;
>
> my $sumform = make_binary('$_[0] + $_[1]');
>
> print "7 + 8 = ", $sumform -> (7, 8), "\n";
>
> print "5 + 3 = ", $sumform -> (5, 3), "\n";
>
>
> sub make_binary
> {
> my $vars = shift;
> return eval "sub { $vars; }";
> }
>
> I understand the mechanism of the closure, but I don't figure out
> how the anonymous subroutine puts the two arguments in $_[0] and in $_[1] ?
Well, the anonymous sub returned by make_binary is
sub { $_[0] + $_[1] };
and it is called with
$sumform -> (7, 8)
so the list (7,8) is passed via @_ to the anonymous sub and retrieved from
there with $_[0] and $_[1].
It's the "normal" way to access the arguments directly.
Maybe the term 'vars' in '$vars' is misleading, since it describes the
actually anonymous sub created with the argument '$_[0] + $_[1]' to
make_binary. Consider
make_binary (100);
There are no vars, but only a constant.
So, $code instead of $vars would be a better variable name in the eval line of
the _generic_ sub make_binary(), which could also be used to make a sub
forking processes or with any other functionality.
hth, joe
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>