develooper Front page | perl.perl6.language | Postings from August 2001

explicitly declare closures???

Thread Next
From:
Dave Mitchell
Date:
August 21, 2001 03:30
Subject:
explicitly declare closures???
Message ID:
200108211030.LAA09706@gizmo.fdgroup.co.uk
Just thought I'd run the following up the flagpole to see if anyone
laughs at it....

Closures are useful, powerful things, but they can also be
dangerous and counter-intuitive, espcially to the uninitiated. For example,
how many people could say what the following should output,
with and without $x commented out, and why:

{
    my $x = "bar";
    sub foo {
	# $x  # <- uncommenting this line changes the outcome
	return sub {$x};
    }
}
print foo()->();

One possibility in perl 6 would be to require outer lexicals used
in an inner sub to be explicitly declared, eg

sub foo { my $x = $_[0];
  return sub { "hello $x" }
}

in perl5, this implicitly creates a closure;
in perl6, this gives a compile time error of 'no such variable $x at line 2'

while

sub foo { my $x = $_[0];
  return sub { my closure $x; "hello $x" }
}

gives the perl5-ish behaviour

ie by default lexicals are only in scope in their own sub, not within
nested subs - and you have to explicitly 'import' them to use them.

The main difficuly is whether globals should be masked by outer lexicals, ie

$x = 'global';
{
  my $x = 'outer lex';
  $foo = sub { $x };
}

should the sub give a 'no such variable $x' compile time error, or
just return the current value of $main::x ??

Maybe whether closures can be implicity created could be governed by
a 'use strict closures' pragma? In which case this "feature" could be added
to perl5 too.

Anyway, I've got to go now, those nice men in the white coats are bringing
me my medicine....

Dave M.


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About