in reply to my, scope, and references

> Or am I complete wrong about scope in the first place,

Indeed!

By returning a reference of a scoped variable you're incrementing it's "reference-counter", such that the variable is not destroyed when leaving the scope.

The variable will be destroyed as soon as you also delete any variable holding that reference, cause the reference counter goes to 0.

Can't give much guidance about how C or C++ behave.

Cheers Rolf

( addicted to the Perl Programming Language)

update

from perlref

       Hard references are smart--they keep track of reference counts for you,
       automatically freeing the thing referred to when its reference count
       goes to zero.  (Reference counts for values in self-referential or
       cyclic data structures may not go to zero without a little help; see
       "Two-Phased Garbage Collection" in perlobj for a detailed explanation.)
       If that thing happens to be an object, the object is destructed.  See
       perlobj for more about objects.  (In a sense, everything in Perl is an
       object, but we usually reserve the word for references to objects that
       have been officially "blessed" into a class package.)

Replies are listed 'Best First'.
Re^2: my and scope
by chayashida (Acolyte) on Mar 28, 2013 at 21:21 UTC

    Hi Rolf,

    Thanks, that helps. I re-read Chapter 8 of the Camel book after my code worked, and I came across the following on page 243:

    Suppose, for example, that you create a hard reference to a lexically scoped array named @array. This hard reference, and the referent it refers to, will continue to exist even after @array goes out of scope. A referent is only destroyed when all the references to it are eliminated.

    So everyone else thinks it's good style?

    I appreciate all the quick responses.

    Chris

      Being able to return a reference safely is fundamental to Perl, and doesn't raise any style-police eyebrows. Consider DBI, where database rows are fetched as an array-ref or hash-ref. Consider JSON, where the thawed JSON data is returned as a reference to a Perl data structure.

      Since you have a C++ background, you might appreciate that Perl references are somewhat analogous to C++11's std::shared_ptr; usually safe to return, because they are referenced counted, and safe to let fall out of scope, because the reference counting also handles destruction.


      Dave

      > So everyone else thinks it's good style?

      This is pluralistic Perl and not a "benevolent dictatorship"!

      (You will always find someone arguing, because of "side effects" or whatever. ;-)

      But honestly as Davido explained, it's fundamental, if you skip these feature it's not Perl anymore.

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        Indeed, it is fundamental. Were it not for returning references safely, we wouldn't have closures, and we wouldn't have blessed reference based objects.


        Dave