grinder has asked for the wisdom of the Perl Monks concerning the following question:

Sometimes I think I have perlman:perldsc down pat, and then a situation comes up that shows me that I still have much to learn.

It's only a minor thing, I wanted to print out a complex data structure (well, a HoAoA) in one statement. It's easy enough to print out an HoA, but I'm getting my braces, ats and arrows mixed up when it comes to printing out at HoAoA.

In the example below, the first print, to print out an HoA seems clear to me (for some definition of clear). In the second example, I don't seem to able to do away with the map operator. I thought I should be about to do something like join( ', ' => @{@{$hoaoa{$_}}->[0] ), but that doesn't work correctly. Is there Another Way To Do It? This is not a call to arms^Wgolf, I want the code to remain more or less readable!

#! /usr/bin/perl -w use strict; my %hoa = ( 'foo' => [ 1, 3, 5 ], 'bar' => [ 4, 5, 6 ], 'rat' => [ 8, 4, 2 ], ); print( "$_ ", join( ', ' => @{$hoa{$_}} ), "\n" ) for sort keys %hoa; print "\n"; =over bar 4, 5, 6 foo 1, 3, 5 rat 8, 4, 2 =cut my %hoaoa = ( 'Foo' => [ [1,2], [3,4], [5,6] ], 'Bar' => [ [3,5], [5,7], [7,9] ], 'Rat' => [ [0,1], [2,1], [4,1] ], ); print( "$_ ", join( ', ' => map { $_->[0] } @{$hoaoa{$_}} ), "\n" ) for sort keys %hoaoa; print "\n"; =over Bar 3 5 7 Foo 1 3 5 Rat 0 2 4 =cut __END__
--
g r i n d e r

Replies are listed 'Best First'.
Re: Printing a hash of arrays of arrays in one statement?
by dragonchild (Archbishop) on Oct 09, 2001 at 19:23 UTC
    What you're trying to get to is the reference to your piece of data. It doesn't matter how deep it is. At that point, you want to dereference it.

    What you were doing was to dereference the array, leaving you with an array. Then ... you tried to take an array and dereference it into an array. That doesn't work as you were expecting (as I'm sure you noticed). :-)

    print( "$_ ", join( ', ' => @{$hoa{$_}[0]} ), "\n" ) for sort keys %hoa;
    You don't need the -> if it's a HoLoL, or whatever. But, you can leave it in if it improves readability for you.
    for my $key (sort keys %hoa) { print( "$key:$_ ", join( ', ' => @{$hoa{$key}[$_]} ), "\n" ) for @{$hoa{$key}}; }
    That'll get you all the way you want to go.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Printing a hash of arrays of arrays in one statement?
by arturo (Vicar) on Oct 09, 2001 at 19:21 UTC
Re: Printing a hash of arrays of arrays in one statement?
by thinker (Parson) on Oct 10, 2001 at 00:01 UTC
    Hi grinder, "Is there Another Way To Do It?" you ask. Here is my shot.
    for (sort keys %hoaoa){ print "$_: "; for(@{ $hoaoa{$_} }){ for ($_){ print "[" . (join ',', @$_) . "]"; } } print "\n"; };
    The rest of the code remains as was.
    I hope this helps.

    thinker