in reply to Finally, C

There are a lot of parallels, and similar syntax, but the Real Important Stuff is very different. Memory management, for three or more.

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

C++ references are like Perl aliases. They have value semantics, but are pointers under the skin. Perl references are like C/C++ pointers.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Finally, C (lexical life)
by tye (Sage) on Dec 16, 2005 at 19:09 UTC
    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