Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: returning reference of a variable defined inside a subroutine.

by davido (Cardinal)
on Feb 04, 2019 at 06:20 UTC ( #1229325=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1229325]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2019-05-22 13:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (140 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!