http://www.perlmonks.org?node_id=922476

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

I feel like I should know this already, but I don't. Is there a shorthand way to get a "column" slice of a 2D array? For example, given @a = ([2,4],[4,5],[8,6],[10,7]); how would I get (4,5,6,7) other than writing for $i (0..$#a) { @b = $a[$i][1] }?

TIA...

Steve

Replies are listed 'Best First'.
Re: Column slice of a 2D array
by BrowserUk (Patriarch) on Aug 26, 2011 at 00:39 UTC
    Is there a shorthand way to get a "column" slice of a 2D array?

    Not really, but map maybe makes it a little clearer:

    @a = ([2,4],[4,5],[8,6],[10,7]);; print map $_->[1], @a;; 4 5 6 7

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Column slice of a 2D array
by ricDeez (Scribe) on Aug 26, 2011 at 04:02 UTC

    Or as a slight variation on BrowserUk's code:

    use Modern::Perl; use Data::Dumper; my @a = ([2,4],[4,5],[8,6],[10,7]); my @b; push @b, $_->[1] for @a; print Dumper \@b;

    prints:

    $VAR1 = [ 4, 5, 6, 7 ];