Hi

I'm a little surprised by the following behavior, I'm chaining generators, such that iterators can be combined:

my $call=0; sub generator (;$) { my $inner_iter=shift; my $dummy; $outer_iter=sub {}; # $outer_iter=sub { $inner_iter->() }; # $outer_iter=sub { $dummy++ }; $call++; print "Call Nr $call\n"; if ($inner_iter){ print $inner_iter."\n"; if ( $inner_iter eq $outer_iter) { print "ERROR !!!\n" } } return $outer_iter; } print generator generator;

I expected that the second anonymous sub $outer_iter to be different from the first, which is also present in the same scope as $inner_iter and hasn't been destroyed yet.

But that's not the case:

/usr/bin/perl -w /tmp/tst.pl Call Nr 1 Call Nr 2 CODE(0x90fa080) ERROR !!! CODE(0x90fa080)

Only uncommenting line 8 or 9 helps, such that an outer variable belongs to the closure of $outer_iter.

Call Nr 1 Call Nr 2 CODE(0x9604880) CODE(0x9623210)

Seems to be an optimization from Perl, kind of constant folding of subs which aren't closures.

So I already have a work around ...

... but out of curiosity, is there any other way to force the creation of a really different instance of a sub, even with the same body but without creating a closure?

Cheers Rolf

UPDATE: I'm still not sure if this should be considered a feature or a bug. It's not the same as with other "data" structures:
sub gen_arr { my $inner_arr=shift; print my $outer_arr=[]; return $outer_arr; } gen_arr gen_arr; #prints ARRAY(0xa179880)ARRAY(0xa179760)

In reply to Avoiding reference of sub optimization by LanX

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.