In general you can't without mucking with the internals (where everything is possible, but also hard until someone writes a module to make it easy).

If however you are not asking about the general case, but already know at closure creation time you will need this, you can return both the target closure and an updater closure:

#!/usr/bin/perl -wl sub gen_counter { my $a = shift; return sub { ++$a }, sub { $a = shift }; } my ($counter, $modifier) = gen_counter(3); print $counter->(); print $counter->(); $modifier->(8); print $counter->(); print $counter->(); # which prints: 4 5 9 10
Or you can combine the two in one closure and use some flag (internal or external) to indicate which action to take. E.g. when using an argument as trigger:
#!/usr/bin/perl -wl sub gen_counter { my $a = shift; return sub { @_ ? $a = shift : ++$a }; } my $counter = gen_counter(3); print $counter->(); print $counter->(); $counter->(8); print $counter->(); print $counter->();
which prints the same

update:I realize my answer tells how to modify a closure, not how to clone it as was asked. For cloning I'd just call the generator again. This is cheap since all generated closures share the code, only the sets of lexicals differ. Or even combine the two (calling the generator as a special closure operation), getting something like:

sub gen_closure { my ($a, $b, $c) = @_; return sub { if ($some_trigger) { # Calculate new $a, $b, $c based on e.g. the # new @_ and the old $a, $b and $c. return gen_closure($new_a, $new_b, $new_c); } # Do the normal closure action on $a, $b and $c here } }

In reply to Re: Rebinding closures, possible? by thospel
in thread Rebinding closures, possible? by bsb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.