babel17 has asked for the wisdom of the Perl Monks concerning the following question:

If I set a variable equal to a reference, is the reference count of the item pointed to by the reference incremented?

I am going to show an example that's slightly more complicated than necessary cause it better represents what I'm trying to accomplish.

my $foo = { by_id => { 0 => { id => 0, name => "bob", other => "Nothing to see here", }, }, }; $foo->{by_name}{bob} = $foo->{by_id}{0};

If I delete $foo->{by_id}{0};, is $foo->{by_name}{bob} still valid?

It's quite easy to simply test this, but I'm more interested in the discussion I hope to provoke in order to better understand perl's internal plumbing.

Replies are listed 'Best First'.
Re: Setting a variable equal to a reference
by ikegami (Patriarch) on Jul 31, 2013 at 02:03 UTC
    delete $foo->{by_id}{0} deletes an element of the hash %{ $foo->{by_id} }.

    The value of that element is a ref. That ref is not referenced by anything else, so it will be freed.

    The referenced hash is is referenced by something else (the ref in $foo->{by_name}{bob}), so it won't be freed.

    So,

    Nothing touches the hash %{ $foo->{by_name} }.

    Nothing touches the ref in $foo->{by_name}{bob} (a copy of the ref that was in $foo->{by_id}{0}).

    The hash referenced by $foo->{by_name}{bob} is not freed.

Re: Setting a variable equal to a reference
by zork42 (Monk) on Jul 31, 2013 at 04:34 UTC
    I'm more interested in the discussion I hope to provoke in order to better understand perl's internal plumbing.
    Devel::Peek might be of interest. It lets you examine the reference count and other internal properties of scalars and other data types.
    It refers to perlguts
    Also, try index-internals
Re: Setting a variable equal to a reference (tryitstosee)
by Anonymous Monk on Jul 30, 2013 at 22:39 UTC

    It's quite easy to simply test this, but I'm more interested in the discussion I hope to provoke in order to better understand perl's internal plumbing.

    If you want to provoke a discussion, ask something different, otherwise, try it to see, because that's all there is to it