Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Lost anonymous subs

by kappa (Chaplain)
on Dec 09, 2004 at 16:02 UTC ( [id://413606]=note: print w/replies, xml ) Need Help??


in reply to Re: Lost anonymous subs
in thread Lost anonymous subs

I have written almost exactly the same piece of code in the reply to diotalevi up there because did not spot your comment. Yes, that helped me to understand things.

I somehow got thinking that closures copy referenced lexicals when created. That was my error.

This is the case when copying really takes place:

my $Big = 'X' x 1000000; sub big { my $big = $Big; return sub { $big }; } my @crefs; push @crefs, big() for 1..10;
--kap

Replies are listed 'Best First'.
Re^3: Lost anonymous subs
by diotalevi (Canon) on Dec 09, 2004 at 17:21 UTC
    Well yes, that's because the = operator copies stuff. There's nothing special about that.
      my @abc; for my $m qw/a b c/ { push @abc, sub { $m }; } print $_->() . "\n" for @abc;
      No assignments and still, those subs each has its own $m. Or does the for my $m creates a new variable on each iteration?
      --kap

        The my() operator has a runtime effect of creating a new variable so each time you start that loop, you have a new variable to have potentially bound to. This also works if you write code like this.

        my @abc; for my $m ( qw/a b c/ ) { push @abc, \ $m; } print @abc
Re^3: Lost anonymous subs
by ysth (Canon) on Dec 10, 2004 at 11:50 UTC
    Not exactly copy, more just steal. Usually lexicals hang around for the next time they go into scope (though they get reset to be empty/undef, they still hold memory). If you take a reference to one (including the case of a closure) and hold the reference until the lexical goes out of scope, the lexical has to get reallocated, since the remaining reference keeps the original.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://413606]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-24 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found