P is for Practical PerlMonks

Slices of 2D arrays?

by Cirollo (Friar)
 on Jun 06, 2003 at 15:21 UTC Need Help??
Cirollo has asked for the wisdom of the Perl Monks concerning the following question:

I have a 2D array, and I want to return just a "column" of the array. For example,
```@ary = ( [1, 2, 3],
[4, 5, 6],
[7, 8, 9] );
So, I want some function that would return (1, 4, 7). The best I've been able to do is this:
```map { \$_->[0] } @ary[0..\$#ary]
This doesn't seem very "nice," and I don't like the map solution because it isn't terribly suggestive of what the code actually does. Anyone have a better way to do this? Maybe something with hash slices? @ary[0..\$#ary][0] doesn't work.

Replies are listed 'Best First'.
Re: Slices of 2D arrays?
by hardburn (Abbot) on Jun 06, 2003 at 15:26 UTC

I think the map statement is fine, but needs something choped off. The 0..\$#ary is unnecessary. You need simply:

```map { \$_->[0] } @ary;

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

Note: All code is untested, unless otherwise stated

(jeffa) Re: Slices of 2D arrays?
by jeffa (Bishop) on Jun 06, 2003 at 15:36 UTC
And if you want to remove that column at the same time:
```use strict;
use warnings;
use Data::Dumper;

my @ary = (
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
);

my @col = map splice(@\$_,0,1), @ary;

print Dumper \@ary, \@col;

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---
```
Re: Slices of 2D arrays?
by broquaint (Abbot) on Jun 06, 2003 at 15:29 UTC
Because slicing takes place on a single array, there isn't a cleaner method than using the map solution you provided, although, you can drop the @ary[0 .. \$#ary] for a simple @ary e.g
```my @ary = ( [ 1 .. 3 ], [ 4 .. 6 ], [ 7 .. 9 ] );
print map \$_->[0], @ary;

__output__

147

HTH

_________
broquaint

Re: Slices of 2D arrays?
by BrowserUk (Pope) on Jun 06, 2003 at 15:52 UTC

You might find my answer to a similar question at Re: Slice of a multidimensional array useful. There are a couple of function definitions there, one of which would do exactly what you want.

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Create A New User
Node Status?
node history
Node Type: perlquestion [id://263706]
Approved by broquaint
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2018-06-23 20:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (125 votes). Check out past polls.

Notices?