in reply to Closures and scope
It seems to me that "my $x" has gone out of scope by the time the anon sub runs...
It has.
is the value still around because there remains a ref to it?
Yes.
If so, what is doing the ref... the anon sub itself?
No, not in my book. The reference to the anonymous sub is a special type of "code ref" called a closure (yes, we all knew that by now). This closure (the code ref) is what holds a reference to the lexical (and not the anonymous sub which is separate from the reference in my book -- especially since the anonymous sub is not recompiled every time you take another reference to it).
So $h holds (something that contains) a reference to the $x that was set to "Howdy" while $g holds a reference to the $x that was set to "Greetings".
Make $x an object and you can see that destroying $h triggers a destructor, etc:
- tye (but my friends call me "Tye")#!/usr/bin/perl -w use strict; sub Obit::new { my( $this, $ref )= @_; my $desc= "$ref"; $desc .= " (${$ref})" if UNIVERSAL::isa( $ref, "SCALAR" ); warn "$desc is born.\n"; return bless $ref, $this; } sub Obit::DESTROY { my $self= shift; my $desc= "$self"; $desc .= " (${$self})" if $self->isa("SCALAR"); warn "$desc has died.\n"; } sub newprint { my $x= Obit->new( \shift ); return sub { my $y= shift; print "${$x}, $y!\n"; }; } $|= 1; { my $h= Obit->new( newprint("Howdy") ); warn "About to destroy \$h.\n"; } warn "\$h is no more.\n"; { my $g= Obit->new( newprint("Greetings") ); warn "About to destroy \$g.\n"; } warn "\$g is no more.\n"; __END__ SCALAR(0x1bbefc0) (Howdy) is born. CODE(0x1bbf074) is born. About to destroy $h. Obit=CODE(0x1bbf074) has died. Obit=SCALAR(0x1bbefc0) (Howdy) has died. $h is no more. SCALAR(0x1bb50d4) (Greetings) is born. CODE(0x1bbf074) is born. About to destroy $g. Obit=CODE(0x1bbf074) has died. Obit=SCALAR(0x1bb50d4) (Greetings) has died. $g is no more.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE (tilly): (tye)Re: Closures and scope
by tilly (Archbishop) on Oct 16, 2000 at 21:14 UTC | |
by tye (Sage) on Oct 16, 2000 at 21:26 UTC | |
by tye (Sage) on Nov 17, 2000 at 21:12 UTC |