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

Hello. I tried to pass an array in my sub as a separate set of args, but discovered that the hole array is a first element of the @_. I cant pick the elements up from @_[ 0] because I use recursion and the sub waits for separate args. So I need to fix the problem only on the first call. Here is some code.
sub permutations { my @array = @_; #my @tmp = @_; #if ($tmp[0][1] != 0) { for (0..$#{$tmp[0]}) { push (@array, $tmp[0] +[$_]); } } #else { @array = @_; } if ($#array == 0) {return [ $array[0] ]; } my @results; my $element; foreach $element (0..$#array) { my @leftovers = @array; my $chosen_one = splice(@leftovers, $element, 1); foreach (&permutations(@leftovers)) { push(@results, [ $chosen_one, @{$_} ]); } } return @results; } @a = permutations($test[2]);
where @test is a 2-dimentional array.

Replies are listed 'Best First'.
Re: Problem with passing array in a sub
by choroba (Cardinal) on May 30, 2014 at 08:15 UTC
    If @test is a 2d array, then passing $test[2] to the subroutine passes an array reference, not an array. To pass the array, you have to dereference it:
    @a = permutations(@{ $test[2] });

    See perllol - Manipulating Arrays of Arrays in Perl for details.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Problem with passing array in a sub
by perlfan (Parson) on May 30, 2014 at 12:16 UTC
    If @test contains arrays as elements, then these are actually arrayrefs. Therefore, you must dereference each element using
    my @row3 = @{ $test[2] };
    This is how nested data structures work in Perl.
Re: Problem with passing array in a sub
by RonW (Parson) on May 30, 2014 at 16:47 UTC

    As previously stated, you are passing a reference, not a list.

    It is also possible to conditionally dereference in your sub:

    if (ref($_[0])) { @array = @{$_[0]}; }
Re: Problem with passing array in a sub
by SHKVal (Initiate) on May 30, 2014 at 14:32 UTC
    Thanks to everyone, this works.)