Below are two cases of inner subs in Perl5 and Python. The first
(do_add3) is a plain nested subroutine, which is in the call chain. The
second (mk_add3) uses a closure. perl5 can't deal with case 1 properly
and warns.
The question is: should Parrot cover case 1 too with :outer and it's
default LexPad, or how would the code be translated to PIR?
NB: currently both are working in Parrot with :outer, second is using
the 'newclosure' opcode..
Examples in other laguages welcome too.
leo
$ cat outer.pl
#!/usr/bin/perl -w
use strict;
sub do_add3 {
my $a = $_[0];
sub add3 {
$a + 3;
}
&add3;
}
print do_add3(20), "\n";
print do_add3(21), "\n";
sub mk_add3 {
my $a = $_[0];
return sub {
$a + 3;
}
}
my $f = mk_add3(39);
print &$f, "\n";
$f = mk_add3(40);
print &$f, "\n";
$ perl outer.pl
Variable "$a" will not stay shared at outer.pl line 7.
23
23
42
43
$ cat outer.py
#!/usr/bin/env python
def do_add3(arg):
a = arg
def add3():
return a + 3
return add3()
print do_add3(20)
print do_add3(21)
def mk_add3(arg):
a = arg
return lambda: a + 3
f = mk_add3(39)
print f()
f = mk_add3(40)
print f()
$ python outer.py
23
24
42
43