in reply to Re^2: Closures and scope of lexicals
in thread Closures and scope of lexicals

I assumed that the closure would use the current value of the scalar

Definitely not. If that were the case, then calling it "binding" (or "closing over") would make no sense. The point is that it binds to the variable in the enclosing scope. So both the sub and any other code with access to that variable can change it.

sub make_private_var_with_accessors { my $var; ( sub { my $val = $var; $val }, # getter sub { $var = shift } # setter ) } my($get,$set) = make_private_var_with_accessors(); $set->(42); print "=".$get->()."\n";
And it's but a hop and a skip to turn that into a POPO class:
{ package PrivateVariable; sub new { my $pkg = shift; my $var; bless { get => sub { my $val = $var; $val }, set => sub { $var = shift }, }, $pkg } sub get { $_[0]->{get}->() } sub set { $_[0]->{set}->($_[1]) } } my $pv = new PrivateVariable; $pv->set(666); print "=".$pv->get()."\n";
Today's latest and greatest software contains tomorrow's zero day exploits.