Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

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

by haukex (Archbishop)
on Feb 03, 2019 at 11:54 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1229317]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-19 16:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found