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

Hi Monks,
I am working on this code and at some point there
,
sub one{ ...more code here irrelevant for this problem... while ($i<=$c) { $direc_data="direc_data".$i; $direc_temp=param($direc_data); $files_data="filenames".$i; $files_temp=param($files_data); $dest_data="dest_data".$i; $dest_temp=param($dest_data); push (@direc_temp,$direc_temp); push (@files_temp,$files_temp); push (@dest_temp,$dest_temp); } return (@direc_temp,@files_temp,@dest_temp); } #End sub ONE


My problem is the value of: @direct_temp,@files_temp and @dest_temp has to be used again in another subroutine, and I can't get the value of the arrays in spec. to work there like,
sub two { (@direc_temp,@files_temp,@dest_temp)= @_; # or (@direc_temp,@files_temp,@dest_temp)= &one; print "Here are all the value found on: @direc_temp,@files_temp and @d +est_temp."; ...more code here irrelevant for this problem... } #End sub two


That's that, any help please? Thank you!!!

Replies are listed 'Best First'.
Re: Subroutine Return Problem
by dorward (Curate) on Aug 17, 2005 at 15:42 UTC

    Arrays in list content get treated as one list. You should return list references instead:

    return (\@direc_temp,\@files_temp,\@dest_temp);

    And then either dereference them or access them as references at the other end of the return.

    See perldoc perlreftut for more.

Re: Subroutine Return Problem
by sk (Curate) on Aug 17, 2005 at 16:09 UTC
    Example on how to pass mutliple arrays as args

    #!/usr/bin/perl -w use strict; randarrays(); # Sub to create two arrays with 5 random elements sub randarrays { my (@a1,@a2) = (); push @a1, (int rand 1000) for (1..5); push @a2, (int rand 1000) for (1..5); printarray(\@a1,\@a2); # \@ makes the call pass by reference. } # print the arrays sub printarray { my ($array1_ref, $array2_ref) = @_; # read the refrences into sc +alars print "array 1\n"; print +($_,$/) for (@{$array1_ref}); # @$ derefrences print $/; print "array 2\n"; print +($_,$/) for (@{$array2_ref}); }

    output

    array 1 610 509 548 628 370 array 2 802 249 464 312 381

    NOTE: the output might change on your machine as they are supposed to be random

Re: Subroutine Return Problem
by tlm (Prior) on Aug 18, 2005 at 01:00 UTC

    There's also short-cut for passing arrays to and from subs that you may come across. Consider the following example:

    sub print_lengths { print scalar @$_, "\n" for @_; } my @a = qw( a b c d ); my @b = 1..8; my @c = localtime; print_lengths \( @a, @b, @c ); # notice the \ before the ( __END__ 4 8 9
    I.e. \( @a, @b, @c ) is equivalent to ( \@a, \@b, \@c ). The \( ... ) evaluates to a list of references to the variables mentioned within the parentheses, as long as these are more than one. (I.e. \( @foo ) doesn't evaluate to \@foo; see perlref for more details.)

    the lowliest monk