http://qs321.pair.com?node_id=439926

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

Hi there. Could someone please tell me how to pass an entire array to a subroutine? I have looked on the net, but have only found ways to pass a certain element on an array, not the whole thing.
Thanks in advance

Replies are listed 'Best First'.
Re: passing arrays to subroutines
by g0n (Priest) on Mar 16, 2005 at 13:08 UTC
    Hi,

    Best way is to pass a reference to the array, then dereference it in the subroutine. Like this:

    use strict; my @array = qw(a b c); mysub(\@array); sub mysub { my @array = @{$_[0]}; foreach (@array) { print $_ } }

    Update: Just read Prasad's post. You can just pass the raw array to the subroutine, in which case @_ in the sub is the content of the array. I prefer to use a reference to make it very explicit that this is a single variable - not a sequence of parameters. Neither method is more correct than the other, although Prasads is simpler.

    g0n, backpropagated monk
Re: passing arrays to subroutines
by BazB (Priest) on Mar 16, 2005 at 13:11 UTC

    A subroutine gets it's arguments as an array (@_), so if you do

    my @array = (1,2,3,4,5); some_sub(@array);
    Within some_sub, @_ will equal the contents of @array.
    However, you probably want to pass the array into the subroutine by reference (see perlref for more):
    my @array = (1,2,3,4,5); some_sub( \@array );
    In that case, the first element of @_, the argument list to some_sub, will be a reference to @array.


    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

      # an array, any array my @bunchOfData = (); # Subroutine: trythis - shows how to pass an array sub trythis { my @array = @_; print "@array\n"; } # where the subroutine is called to do something with the array &trythis(@bunchOfData);
Re: passing arrays to subroutines
by neniro (Priest) on Mar 16, 2005 at 13:40 UTC
    There are two ways of passing data to a subroutine:

    - call by value
    - call by reference

    References are always a good idea - especially if you have large or complex datastructures, but using values is much easier in the beginning. Here's an example that I've posted earlier this day on a german perl-community site. Two array-references gets passed to a function in an anonymous hash:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @numbers = (1..10); my @words = qw(hello world outside); function( {NUMBERS=>\@numbers , WORDS=>\@words} ); exit; sub function { die "no parameter!\n" unless @_; my %opt = %{ shift @_ }; print Dumper \%opt; my @i_words = $opt{WORDS}; print Dumper \@i_words; my @i_numbers = $opt{NUMBERS}; print Dumper \@i_numbers; }
      There are two ways of passing data to a subroutine:

      - call by value
      - call by reference

      Actually, there's also:

      - call by name
      - call by copy-restore
      - call by result
      - call by push value
      - call by need
      - call by macro expansion

      See Parameter (Computer Science) on Wikipedia.

      Most (all?) of these can be done in Perl. In Perl, it really comes down to two things:

      1) Parameters are passed as a list of scalars.
      2) The caller and the callee have to agree on what those scalars mean.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Re: passing arrays to subroutines
by gopalr (Priest) on Mar 16, 2005 at 13:13 UTC
    @arr=('1', '2', '3'); test(\@arr); sub test { my $a=@_[0]; print "\n@$a"; }
      my $a=@_[0];

      Unpacking @_ with explicit subscripts is inefficient and unsightly. Using an array slice in a scalar context is also messy.

      my ($a)=@_;
      or
      my $a=shift;
Re: passing arrays to subroutines
by prasadbabu (Prior) on Mar 16, 2005 at 13:06 UTC
    @a= (1, 2, 3); &test(@a); sub test {my (@b)= @_; pirnt "@b"; }

    If you want to pass more than one array you can make use of reference. see perlref

    Prasad

      That doesn't pass an array into the sub. It passes a list into the sub. In fact, you cannot pass an array into a sub in Perl - the best you can do is passing a reference, either explicitely using \ (caller in charge), or implicitely using a prototype (callee in charge).

        Just to expand on this point for the OP's benefit, consider:

        use strict; use Dumpvalue; my $dumper = Dumpvalue->new(); my @a = (3, 1, 4, 1); my @b = (5, 9); my @c = (2, 6, 5); sub ex1 { map 10*$_, @_; } $dumper->dumpValue([ex1(@a)]); print "\n"; # array refs sub ex2 { map scalar @$_, @_; } $dumper->dumpValue([ex2(\@a, \@b, \@c)]); print "\n"; # implicit array refs through prototypes sub ex3 (\@\@\@) { map scalar @$_, @_; } $dumper->dumpValue([ex3(@a, @b, @c)]); print "\n"; __END__ 0 30 1 10 2 40 3 10 0 4 1 2 2 3 0 4 1 2 2 3
        Note that the bodies of ex2 and ex3 are identical. IMO, however, ex2 is superior, because it can take as arguments any number of array refs, whereas ex3 must take exactly three arrays as arguments.

        Follow-up question: is there any way to define a sub that takes as input one or more arrays?

        the lowliest monk

Re: passing arrays to subroutines
by perlfan (Vicar) on Mar 16, 2005 at 14:47 UTC
    Pass by reference - this is what I usually do:
    my @array = qw(a b c d e f); my @new_array = do_something(\@array); #<- note the "\" sub do_something { my $array_ref = shift; my @new = (); foreach (@{$array_ref}) { #<- treat the ref as an array # do some stuff like build @new } return @new; }
    You can also return ref's which means you can return mulitiple array, hash, and scalar references by using as a list with out them getting all flattened out together.

    To give you a visual of what an array looks like versus an array reference, Data::Dumper would show:

    For '@array' outside the subroutine:
    $VAR1 = a $VAR2 = b ..etc
    For '$array_ref' inside the subroutine:
    $VAR1 = [a,b,c,d,e,f]
    This is because $array_ref points to an anonymous array passed to to the subroutine while @array IS the array.