Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass two lists to a Perl subroutine?

Is it possible to pass two lists to a sub in Perl, for example:

sub Foo {
 my(@list1,@list2) = @_;

}

I know I could make @_ two lists, with each sublist being the desired argument, I'm just wondering if there is a cleaner way

like image 295
Mike Avatar asked May 21 '10 16:05

Mike


2 Answers

Well if you want two arrays you could use a prototype:

sub foo (\@\@) {
   my $arr1 = shift;
   my $arr2 = shift;

   # Access arrays as references
}

foo( @wiz, @waz );  # @wiz and @waz won't be flattened.

But there are many ways to get around prototypes, and I prefer to avoid them in most places. You can simply skip the prototype and manually pass references:

sub foo {
   my $arr1 = shift;
   my $arr2 = shift;

   # Access arrays as references
}

foo( \@wiz, \@waz ); # Pass in wiz/waz as refs
foo( [1,2,4],[3,5,6] );  # Hard coded arrays

If you haven't worked with references at all, check out perlreftut for a nice tutorial.

like image 184
daotoad Avatar answered Oct 05 '22 17:10

daotoad


If you pass two lists by value ... you're going to get one big list in @_.

my(@list1,@list2) = @_; doesn't make any sense:

#!/usr/bin/perl

sub test
{
    my (@a, @b) = @_;

    print "@a\n";
    print "@b\n";
}

my @array1 = (1,2,3);
my @array2 = (5,6,7);

test(@array1, @array2);

This will end up printing:

1 2 3 5 6 7
<blank line> 

To pass two arrays, you'd need to pass them by reference:

test(\@array1, \@array2);

And in your sub you'd need to treat them as references:

sub test
{
    my ($arrayRef1, $arrayRef2) = @_;
    print "@$arrayRef1\n";
    print "@$arrayRef2\n";
}
like image 27
Brian Roach Avatar answered Oct 05 '22 17:10

Brian Roach