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

How do i pass an array or mutiple arrays to a function? Thank you in advance.

Replies are listed 'Best First'.
Re: Passing arrays
by rchiav (Deacon) on May 04, 2001 at 23:08 UTC
    The best way to do this all depends on what you're looking to do with the data.

    The easiest way is to just pass the array -

    mysub(@myarray);
    Now you're not going to be able to modify the array, just use the data that's passed. You're also not going to be able to tell which things were actually part of that array. Meaning if you do..
    somesub(@somearray, $somescalar);
    They are all passed to the sub as one big list. This also means that if you pass two arrays, they are passed as one big list.. without a good way to tell them apart.

    Now.. you can explore the wonderful world of refrences if you want to modify the actual arrays and/or be able to differentiate between the two arrays. To pass a refrence, you do the following..

    somesub(\@somearray, \$somescalar);
    Now what's passed is actually two scalars that happen to be refrences to your data (not just some copy of the contents of those variables).

    Now to access them, you need to derefrence them. There are various methods to do this. Instead of me trying to reinvent the wheel (and doing it much poorer), I'll defer to some articles that do a much better job of this than I can. For starters, read one of merlyn's articles. There's also perlref and perldsc.

    Hope this helps..
    Rich

Re: Passing arrays
by isotope (Deacon) on May 04, 2001 at 22:58 UTC
    The easiest way is to pass a reference. See perlman:perlref. Here's a quick example:
    sub example { my $array1 = shift; my $array2 = shift; push(@{$array1}, 'somevalue'); print $$array2[2]; } my @first_array = (0..9); my @second_array = ('a'..'z'); example(\@first_array, \@second_array);


    --isotope
    http://www.skylab.org/~isotope/
Re: Passing arrays
by Masem (Monsignor) on May 04, 2001 at 22:57 UTC