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

Re: Multi dimentions to a single dimentional array

by rubasov (Friar)
on Jan 23, 2010 at 12:54 UTC ( #819177=note: print w/replies, xml ) Need Help??

in reply to Multi dimentions to a single dimentional array

biohisham and ikegami explained cleanly how you can reference the elements in the first "column" one-by-one in a for loop. If you want to join these elements, you can extend that idiom like this (by storing the values in a new array called @column):
use strict; use warnings; my @AoA = ( [ 'Jan', 10, 20 ], [ 'Feb', 15, 25 ], [ 'Mar', 30, 33 ] ); my @column; for my $month_data (@AoA) { push @column, $month_data->[0]; } print join( ' ', @column ), "\n";
However you can use shorter and cleaner constructs, if you don't need them one-by-one, but all of them at once, as an array for the "column". Try this:
use strict; use warnings; my @AoA = ( [ 'Jan', 10, 20 ], [ 'Feb', 15, 25 ], [ 'Mar', 30, 33 ] ); print join( ' ', map {$_->[0]} @AoA ), "\n"; # prints 'Jan Feb Mar' print join( ' ', map {$_->[1]} @AoA ), "\n"; # prints '10 15 30'
The map expression above (map {$_->[0]} @AoA) creates and returns a new array by implicitly iterating through your array refs ("lines", $AoA[0], $AoA[1] ...), taking the first element ("column", $AoA[0][0], $AoA[1][0] ...) from each and constructing the new array from them. (But of course, if you think this is too much for once, just stick with the first and easier version.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://819177]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2018-02-17 22:26 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (250 votes). Check out past polls.