go ahead... be a heretic PerlMonks

### Re^2: Parsing complex data

by ikegami (Pope)
 on Jul 15, 2005 at 15:38 UTC ( #475254=note: print w/replies, xml ) Need Help??

in reply to Re: 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.

Replies are listed 'Best First'.
Re^3: Parsing complex data
by Limbic~Region (Chancellor) on Jul 15, 2005 at 15:41 UTC
ikegami,
Limbic's solution has problems

It certainly does. This is one of those posts where my brain auto-corrected missing and incorrect information. After the initial post I realized it was lacking and noted it. Thanks for spending more than 2 seconds reading the question before replying - it is afterall Friday.

Cheers - L~R

Create A New User
Node Status?
node history
Node Type: note [id://475254]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2020-05-31 14:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
If programming languages were movie genres, Perl would be:

Results (173 votes). Check out past polls.

Notices?