http://www.perlmonks.org?node_id=1229325


in reply to returning reference of a variable defined inside a subroutine.

You can use Devel::Peek to inspect the reference count. Perl won't reap the underlying array until that array's reference count has dropped to zero. Here's an example:

use Devel::Peek qw(SvREFCNT); sub return_array { my @array = (42); print "\@array declared. Refcount: ", SvREFCNT(@array), "\n"; my $ref = \@array; print "A reference has been taken to \@array. Refcount: ", SvREFCN +T(@array), "\n"; return $ref; } my $aref = return_array(); print "Function returned a reference. Refcount:", Devel::Peek::SvREFCN +T(@$aref), "\n";

The output:

@array declared. Refcount: 1 A reference has been taken to @array. Refcount: 2 Function returned a reference. Refcount:1

Because a reference was returned, and that reference stays in scope for the remainder of the script, the reference count never drops below 1. Since the reference count never drops below one, the array is never reaped. So this is a safe process. In C it would be quite easy to mistakenly return a pointer to an entity that will not persist past the duration of the function call. But C isn't protected by a reference count; you have to handle memory management yourself. In C++ you do have the concept of a shared pointer, and those are reference counted with built-in memory management that more closely resembles Perl's reference counting system.


Dave