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

I'm very new to perl. I have a two dimensional array, say $tmp[0][0], etc. I want to pass just one dimension at a time to a subroutine. $tmp[0]... &my_subroutine($tmp????)

How is that done so that the subroutine can examine it as $tmp[0], $tmp[1], etc?

sub my_subroutine($) { my @tmp_arry = @_; print $tmp_arry[0]; ... }

Edited by Chady -- moved text outside code tags.

Replies are listed 'Best First'.
Re: passing array
by jeffa (Bishop) on Jul 20, 2004 at 20:00 UTC

    Here is how i might do it:

    my @array = ( [1,2,3], [4,5,6], [7,8,9], ); my_subroutine($_) for @array; sub my_subroutine { my $thing = shift; print $thing->[0]; }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: passing array
by stajich (Chaplain) on Jul 20, 2004 at 19:37 UTC
    Dereference
    &my_subroutine(@{ $tmp[0] });
    The @{ } tell perl to treat the scalar inside as an array.
Re: passing array
by gaal (Parson) on Jul 21, 2004 at 05:42 UTC
    You got good replies so far, but note that the way this data structure works, it's easy to slice up the matrix in one direction but hard to do it in the other. If you only ever need to do your slicing one way, follow the examples above to design the order of the dimensions in your array. If your data is numerical and you'll need to slice it either way, you might want to take a look at PDL. If that doesn't help... you may need to pass an explicit index.

    BTW, you probably don't need the ($) to my_subroutine. Subroutine templates in Perl are unlinke what you may be used to from other languages.