Perl lexicals are like C auto variables, which are generally at the top of the stack.

That is somewhat true and somewhat misleading.

Perl lexicals don't go on the stack. They can't because of the key difference between Perl lexicals and C lexicals: The lifetime of C lexicals matches their scope while Perl lexicals can live forever.

That is, a C lexical is destroyed unconditionally when its scope is exitted. Perl lexicals are initialized (often creating a new instance) when their scope is entered and have one reference to them removed when the scope is exitted. The variable instance will only be destroyed if that was the only remaining reference to it.

So having a sub return a pointer/reference to one of its lexical variables in C/C++ is "a bug" (as it storing a pointer/reference into something that will live past the call into the sub). Having a Perl sub (or 'do' block, etc.) return a reference to one of its lexicals is just fine (as is storing references to any variables anywhere -- though making circular references causes other, less severe, problems).

- tye        


In reply to Re^2: Finally, C (lexical life) by tye
in thread Finally, C by Ido

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.