Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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] }?

TIA...

Steve

Comment on Column slice of a 2D array
Select or Download Code
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;

    prints:

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2014-12-27 00:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls