Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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.)


Comment on Re: Multi dimentions to a single dimentional array
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://819177]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2014-09-16 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (33 votes), past polls