rq-2102 has asked for the wisdom of the Perl Monks concerning the following question:

I have a sub in a program that returns multiple arrays. As of right now i'm assigning all these to temporary arrays and then pushing them onto arrays in the main code and then undefing the temps. My question is, is there a faster/better way to do this (i.e incorporating the push statement into the sub call).

thanks
---------
:|

Replies are listed 'Best First'.
Re: Returning arrays to a push statement
by data64 (Chaplain) on Oct 29, 2001 at 09:04 UTC

    First let me make sure I understand your question correctly, since it is not very clear what exactly you are looking for.( Posting some code would have helped.)

    You have code of the type

    use strict; use warnings; use vars( @list0, @list1, @list2 ); sub DoSomething() { my( @localList0, @localList1, @localList2); #do something here my( @tempList ) = ( \@localList0, \@localList1, \@localList2 ); return @tempList; } #main program my @tempList = DoSomething(); push @list0, @$tempList[0]; push @list1, @$tempList[1]; push @list2, @$tempList[2];

    Assuming above (or something similar) is what you are looking at improving, I would suggest passing in references to the array into the subroutine. The subroutine can then push stuff onto the right arrays without the need of temporary arrays.

    use strict; use warnings; use vars( @list0, @list1, @list2 ); sub DoSomething( \@ \@ \@ ) { my( $listRef0, $listRef1, $listRef2) = @_; #do something here push @$listRef0, somelist; push @$listRef1, somelist; push @$listRef2, somelist; } #main program DoSomething( \list0, \list1, \list2 );
    The other, less preferred option would be to directly refer to the outer arrays from within the subroutine. Depending on the size of your program this might be clearer, especially if your script needs to be maintained by someone not familiar with perl style references. However, if the subroutine will be in a separate module, you want to avoid doing this at all costs.
    use strict; use warnings; use vars( @list0, @list1, @list2 ); sub DoSomething() { #do something here push @list0, somelist; push @list1, somelist; push @list2, somelist; } #main program DoSomething();
Re: Returning arrays to a push statement
by chromatic (Archbishop) on Oct 29, 2001 at 08:24 UTC
    Yes. Feel free to do just that.