On Mon, 31 Dec 2007 14:43:44 -0800, gst wrote:
> iirc, in C if I store somwhere a pointer to a "stack" value (e.g.:
> call a function with an auto variable, return its pointer) i know i'm
> going to mess things, since that piece of data will be most probably
> overwritten by subsequent calls.
> 
> if I do the same in Perl (with a hard ref), do I have any guarantee
> that the same behavior (implicit aliasing) does - or does not (every
> new scalar is guaranteed to not alias the old non existant value) -
> apply?

I'm not entirely clear what it is you're either trying to do or trying to
avoid.  Usually one takes a copy of a subroutine argument to work on it:

        sub frobble {
                my $arg = shift;  # same as my $arg = $_[0];
                # Work on $arg
        }

The @_ array contains aliases for the arguments, so that you can change
them (this is uncommon and almost always a bad design):

        sub fnord { $_[0]++ }
        fnord( my $x = 42 );  # $x == 43
        fnord( 42 );  # Error: attempt to modify r/o value

Perl does reference-based garbage collection, so as long as a reference
(this is an internal reference, not a perlref sort of reference) to
something exists, that thing will not go away.  So a subroutine can
create a new variable, return a reference to it, and as long as the
storage that receives that reference is in use, the storage the reference
refers to will be retained, even if it becomes anonymous.

If you return a reference to some element of @_, the aliasing means it is
as if you had enreferenced whatever was passed in that argument position.

If that doesn't answer your question, I suggest you read perlref and post
some sample code you are concerned about.  If you've written something
that involves just package and/or lexical variables, subroutine calls,
enreferencing and dereferencing operators, and use of the @_ array and are
wondering whether the resulting behavior can be counted on being
consistent on every perl (5) and every platform, the answer is yes.

-- 
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to