Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Column slice of a 2D array

by cormanaz (Chaplain)
on Aug 26, 2011 at 00:25 UTC ( #922476=perlquestion: print w/replies, xml ) Need Help??
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] }?



Replies are listed 'Best First'.
Re: Column slice of a 2D array
by BrowserUk (Pope) 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;


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://922476]
Approved by BrowserUk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2016-10-25 01:00 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (313 votes). Check out past polls.