http://qs1969.pair.com?node_id=475254


in reply to Re: Parsing complex data
in thread Parsing complex data

L~R's solution has problems:

$data_array_ref = [ mykey1 => {firstkey => 'firstvalue', secondkey => 'secondval' }, mykey2 => {ninza => 'turtle', 'Hurricane' => 'Dennis'}, mykey3 => [ ['one', 'two', 'three'] ], mykey4 => [ [4, 5, 'three'], [6, 7, 'four'], [8, 9, 'five'] ], ]; for ( @$data_array_ref ) { print "$_ =>"; if ( ref $_ eq 'ARRAY' ) { print join ", ", @$_; } else { print join ", ", sort values %$_; } print "\n"; } __END__
output ====== mykey1 => HASH(0x1abefc0) =>firstvalue, secondval mykey2 => HASH(0x1abf0a4) =>Dennis, turtle mykey3 => ARRAY(0x1ab5148) =>ARRAY(0x1ab50d0) mykey4 => ARRAY(0x1ab52f8) =>ARRAY(0x1ab5190), ARRAY(0x1ab5208), ARRAY(0x1ab5280 +)

My solution:

$data_array_ref = [ mykey1 => {firstkey => 'firstvalue', secondkey => 'secondval' }, mykey2 => {ninza => 'turtle', 'Hurricane' => 'Dennis'}, mykey3 => [ ['one', 'two', 'three'] ], mykey4 => [ [4, 5, 'three'], [6, 7, 'four'], [8, 9, 'five'] ], ]; my $i = 0; while ($i < @$data_array_ref) { my $key = $data_array_ref->[$i++]; my $val = $data_array_ref->[$i++]; print "$key => "; if (ref($val) eq 'HASH') { print join ', ', values %$val; } else { print join ', ', map { @$_ } @$val } print "\n"; } __END__ output ====== mykey1 => firstvalue, secondval mykey2 => turtle, Dennis mykey3 => one, two, three mykey4 => 4, 5, three, 6, 7, four, 8, 9, five

It be somewhat easier if your topmost data structure was a hash, not an array.

map { @$_ } @$_ flattens a ref to an array of arrays of scalars, as opposed to @$_ which only flattens a ref to an array of scalars.