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 haukex (Chancellor)
on Feb 03, 2019 at 11:54 UTC ( #1229317=note: print w/replies, xml ) Need Help??


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

Perl uses a method called reference counting to ensure that memory stays allocated as long as there is at least one reference pointing to it. The code you've showed is fine. On every call of the sub, a new array will be allocated, and the reference pointing to it will keep it alive, even after the sub ends.

sub foo { my $m = shift; my @array = ($m*1, $m*2, $m*3); return \@array; } my $x = foo(2); my $y = foo(3); use Data::Dump; dd $x; # [2, 4, 6] dd $y; # [3, 6, 9] $x = undef; # *now* the memory for that array is freed

Update: For more details, see perlref.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2019-10-19 11:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?