Returning reference to an array

A

Andrew Fleet

Hi,
I'm looking at returning a reference to an array I create within a
subroutine.

I could do this...

sub foo {
my @theArray;

<snip>

return \@theArray;
}

This works however I'm concerned I'm returning a reference to stack data. I
heard if I used 'local' rather than 'my' the array will always exist (it's
global), but using 'my' I'm creating a temporary stack based
array that will then be cleaned up when the subroutine returns, hence my
reference will be invalid.

So...my or local?

Thanks

Andy
 
E

Eric J. Roode

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I'm looking at returning a reference to an array I create within a
subroutine.

I could do this...

sub foo {
my @theArray;

<snip>

return \@theArray;
}

This works however I'm concerned I'm returning a reference to stack
data. I heard if I used 'local' rather than 'my' the array will always
exist (it's global), but using 'my' I'm creating a temporary stack
based array that will then be cleaned up when the subroutine returns,
hence my reference will be invalid.

So...my or local?

Use 'my'. You heard wrong. Perl data structures are cleaned up when
there are no more remaining references to them. When you declare
@theArray with 'my', a new data structure is created. When you return
\@theArray and presumably store that return value into a variable, there
is still an extant reference to the array. When all references to the
array go out of scope or are reassigned, then the array will be garbage-
collected.

For your future reference, comp.lang.perl is a defunct newsgroup. Please
post general perl questions to comp.lang.perl.misc; you'll get a better
response there.

- --
Eric
$_ = reverse sort $ /. r , qw p ekca lre uJ reh
ts p , map $ _. $ " , qw e p h tona e and print

-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 7.0.3 for non-commercial use <http://www.pgp.com>

iQA/AwUBP5u1mWPeouIeTNHoEQIm8ACePbY4ajAWypokHBdPDyAamPdz+NcAoJSX
kYDhlG/aEBKkK9BYsmP08671
=6UqS
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top