Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Slices of 2D arrays?

by Cirollo (Friar)
on Jun 06, 2003 at 15:21 UTC ( #263706=perlquestion: print w/ replies, xml ) 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.

Comment on Slices of 2D arrays?
Select or Download Code
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;


    (the triplet paradiddle with high-hat)
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



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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2016-05-27 03:02 GMT
Find Nodes?
    Voting Booth?