Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to generate two array, because the process is basically the same (only need to take the different part), I generated them at the same time in the same subroutine, if I try to return either one, it works fine, but I need two array, if I make another subroutine, it seem just copy the other sub, it does not make sense, What should I do? Thanks in advance!!!
  • Comment on Is it possible to return two array by the same subroutine?

Replies are listed 'Best First'.
Re: Is it possible to return two array by the same subroutine?
by Ovid (Cardinal) on Apr 30, 2003 at 17:21 UTC

    Use references.

    sub foo { my @array1 = stuff(); my @array2 = flibberty(); return \@array1, \@array2; }

    See perldoc perlref for more information.

    Cheers,
    Ovid

    New address of my CGI Course.
    Silence is Evil (feel free to copy and distribute widely - note copyright text)

Re: Is it possible to return two array by the same subroutine?
by broquaint (Abbot) on Apr 30, 2003 at 17:28 UTC
    Since subroutines return lists, and arrays are flattened in list context, your arrays are probably being flattened into a single list. What you probably want is to return 2 array references, so the 2 arrays remain distinct 'objects' e.g
    sub foo { my @x = 1 .. 5; my @y = reverse 1 .. 5; return \@x, \@y; } my($ar1, $ar2) = foo(); print "array 1 - @$ar1\n"; print "array 2 - @$ar2\n"; __output__ array 1 - 1 2 3 4 5 array 2 - 5 4 3 2 1
    See. the likes of tye's References quick reference and japhy's "list" is a four letter word for more info on references and contexts.
    HTH

    _________
    broquaint