Re: get a column out of a 2d array



On 10/3/07, Mahurshi Akilla <mahurshi@xxxxxxxxx> wrote:

is there an easy way (without iterating through the array) to get a
specified column out of a 2d array?

There is no way in general, easy or hard, to get a column out of an
array in Perl without using iteration, even if the iteration is hidden
inside a map, foreach, or something similar. So, your answer is "no".

i know you can get it with rows using ( $my2ndrowref = @array[1] ) but
i don't want to transpose all my data right now for this.

I think you mean something like this:

my @second_row = @{ $array[1] };
print "Second row: @second_row\n";

But now you want a column, instead of a row. Well, if there actually
is a column there (we'll assume your data is rectangular), it's easy
to extract a copy with map:

my @second_col = map $_->[1], @array;
print "Second column: @second_col\n";

That's a copy, instead of the original data. If you want to modify it,
there's probably a better way to do that.

Does that do anything good for you? Good luck with it!

--Tom Phoenix
Stonehenge Perl Training
.



Relevant Pages

  • Re: Readline using foreach and while
    ... condition is checked at the start of each iteration, if the array ... map doesn't recheck the count ... the passed list for each iteration. ... @ary, which comes from a scope outside this sub, now contains (h, a, b, ...
    (comp.lang.perl.misc)
  • Re: Readline using foreach and while
    ... condition is checked at the start of each iteration, if the array is ... the line with the map statement, it does indeed contain 'd' at the end. ... passed list for each iteration. ...
    (comp.lang.perl.misc)
  • Re: When MUST you use map ?
    ... > In my limited experience with perl, I've never had to use the 'amp' ... > So, when do you HAVE to use 'map', when no other option makes sense?! ... Reverse an array without using reverse: ...
    (perl.beginners)
  • Re: Readline using foreach and while
    ... condition is checked at the start of each iteration, if the array is ... the line with the map statement, it does indeed contain 'd' at the end. ... passed list for each iteration. ... this behavior is part of what separates map from for/foreach. ...
    (comp.lang.perl.misc)
  • Re: can map/collect return fewer values than are found in the target?
    ... The difference seems to be that Ruby's interpretation of map seems to be ... stricter than Perl's, e.g. for one item in the original Array, there's ... map/collect in ruby seems very similar to map in perl except that in perl ...
    (comp.lang.ruby)