Returning reference to an array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Fleet

    Returning reference to an array

    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


  • Eric J. Roode

    #2
    Re: Returning reference to an array

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

    "Andrew Fleet" <areconsulting@ earthlink.net> wrote in
    news:Yyimb.734$ Px2.385@newsrea d4.news.pas.ear thlink.net:
    [color=blue]
    > 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?[/color]

    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/AwUBP5u1mWPeouI eTNHoEQIm8ACePb Y4ajAWypokHBdPD yAamPdz+NcAoJSX
    kYDhlG/aEBKkK9BYsmP086 71
    =6UqS
    -----END PGP SIGNATURE-----

    Comment

    Working...