good chemistry is complicated,and a little bit messy -LW PerlMonks

### Column slice of a 2D array

by cormanaz (Chaplain)
 on Aug 26, 2011 at 00:25 UTC 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

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;

prints:

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

Create A New User
Node Status?
node history
Node Type: perlquestion [id://922476]
Approved by BrowserUk
help
Chatterbox?
and the grasshoppers chirp...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2018-05-26 08:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (193 votes). Check out past polls.

Notices?