in reply to Sub Definitions Within Subs: Best Way to Exploit

Unfortunately, any subroutine that you define like that will be put into the namespace of the package that it's resident in. Thus, you cannot have lexically scoped subroutines. From what I understand, we will have lexically scoped subs in Perl6.

What you want is a closure:

my $bar = sub { print shift }; sub foo { print "Hello\n"; $bar->( "Saluton mondo!\n" ); } foo(); $bar->( "Hello world!\n" );

Hmm... as I recall, the proper definition of a closure is an anonymous code reference that contains a reference to a lexically scoped variable that is defined outside of itself. Since this example doesn't really do that, is it, strictly speaking, a closure?

Cheers,
Ovid

Vote for paco!

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: Sub Definitions Within Subs: Best Way to Exploit
by perrin (Chancellor) on Oct 11, 2001 at 05:20 UTC
    Actually, it doesn't need to be anonymous or a code ref to be a closure; it just has to refer to lexical variables defined outside of its scope. This is a closure:
    my $foo; sub bar { print $foo; }
    Any further changes to the value of $foo in the future will not change the private value that bar() now has.
      It does need to be inside another sub. The code has to be something like:
      sub baz { my $foo=shift; sub bar { print $foo; } } baz("abc"); bar; baz("123"); bar;
      which will print abcabc. The change to the $foo variable in the second call does not affect subroutine bar. It has a 'closed', localised and personal $foo variable, that cannot be changed by outside influences - only by bar itself. Thus the name 'closure'.
        Your explanation makes sense, but it isn't correct. Based on the number of times I've had this conversation, I'd say there is massive misunderstanding around the word "closure" in the Perl community.

        Here's a definition of closure from Damian Conway:

        "In Perl, a closure is just a subroutine that refers to one or more lexical variables declared outside the subroutine itself" - OO perl, p 56.

        I grabbed that quote from a post on the Perl6 list, but I've used that as my standard definition of closure ever since the book came out. It's really the only one I've seen that makes sense.

        Note that merlyn also agrees with me, as shown here in this post to the mod_perl list.