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
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
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.
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";
}
sub in_both{
my %a = @_;
my @first = @{$a{first}};
my @second= @{$a{second}};
}
@in_both=in_both(first=>[@names_one], second=>[@names_two]);