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

I have got several arrays in a program and want to run a subroutine on them. When i try to put them into the subroutine using subroutine(array1,array2,array3...);, followed by my (subarray1,subarray2,subarray3..)=@_ it seems that the data from all the arrays is concatenated into subarray1. Can you tell me how i can send multiple arrays into a subroutine individually. Thanks

Replies are listed 'Best First'.
Re: getting arrays into subroutines
by BrowserUk (Patriarch) on Aug 12, 2002 at 17:47 UTC

    Short answer: Pass references to the arrays as:

    ... sub something { my ($ary_ref1, $ary_ref2, $ary_ref3) = @_; ... } ... something( \@ary1, \@ary2, \@ary3 ); ...

    Long answer: Read perlreftut and perlref

Re: getting arrays into subroutines
by mfriedman (Monk) on Aug 12, 2002 at 19:16 UTC
    As others have aluded to, you cannot pass an array to a subroutine, only a list of scalar values. When you pass multiple arrays as mysub(@array1, @array2, @array3), the three arrays become concatenated into one big list. The solution is to use references to the arrays. Be careful that you copy the dereferenced array unless you want to change the values of the original array. Example:

    my @a1 = qw/a b c d e f g/; my @a2 = qw/h i j k l m n/; sub mysub { my ($r1, $r2) = @_; # make a copy of the first array my @a1_copy = @{ $r1 }; $a1_copy[2] = 'blah'; # only affects this copy # tweak the original @a2 $r2->[2] = 'blah; # affects @a2 } mysub(\@a1, \@a2);
Re: getting arrays into subroutines
by Rex(Wrecks) (Curate) on Aug 12, 2002 at 17:40 UTC
    Simple answer, you can't! You can only pass scalar values to a sub.

    You can however pass references, I recomend looking at perlref.

    Update: One other thing, by searching this site, or just wandering through the Code Catacombs, you will find a ton of examples on how to do this.

    "Nothing is sure but death and taxes" I say combine the two and its death to all taxes!