Charles DeRykus said:
Charles DeRykus said:
On 10/7/2013 9:15 AM, Rainer Weikusat wrote:
[variable lifetimes]
...
Wouldn't something like this effectively encapsulate $foo and act as a
closure though:
package main; ...
package MyFoo;sub add_something { our $foo; return $foo += $_[0]; };
package main; ...
package MyFoo;sub add_something { our $foo; return $foo += $_[0]; };
package main;
$MyFoo::foo = -15;
print MyFoo::add_something(3), "\n";
I overreached with 'effectively' perhaps but didn't intend that it was
unassailable. A $_foo might have helped. But it's a bit of a stretch
to break it accidentally too.
The point was supposed to be that our is genuinely different from my
because it doesn't create a perl-level object (it may do so
accidentally, but that's an implementation detail which can be ignored)
but a short (that is, not fully-qualified) name referring to an object
associated with the symbol-table of the package the our resides in (in
order to prevent "use strict 'vars'" from complaining about such an
object being used without a fully-qualified name): With your
add_something, not the scope of the object referred to by $foo is
restricted but the scope of the short name $foo. This code
-------
use strict;
package MyFoo;
sub add_something { our $foo; return $foo += $_[0]; };
$foo = 5;
package main;
print MyFoo::add_something(3), "\n";
--------
won't compile because the $foo name is used outside of the scope of the
our declaration but this code
--------
use strict;
package MyFoo;
sub add_something { our $foo; return $foo += $_[0]; };
our $foo = 5;
package main;
print MyFoo::add_something(3), "\n";
--------
will because a name referring to the same object is declared in both
scopes.
In contrast to this, both the 'state' feature and the trick with
creating a my-variables in a surrounding scope end up creating an object
which is private to the subroutine in question and will keep its value
between invocations of that.