in reply to printing complex data structures

Hint : it's much easier to traverse deep data structure when iterating over values instead of keys, especially if you never need the keys.

Please note my naming convention using trailing h_ and a_ to denote hash refs and array refs.

i.e. h_codes -> h_planet -> a_aa see included dump

Like this it's obvious when to use @$a_ and %$h_ for dereferencing ...

use strict; use warnings; use Data::Dump qw /pp dd/; my %aas = ( 'serine' => ['TCA', 'TCC', 'TCG', 'TCT'], 'proline' => ['CCA', 'CCC', 'CCG', 'CCT'] ); my %codes; $codes{'earth'} = \%aas; $codes{'mars'} = { 'serine' => ['QWZ', 'QWX', 'QWW'], 'proline' => ['ZXZ', 'ZXX', 'ZXQ', 'ZXW'] }; dd \%codes; # dump for clarity base_code (\%codes); sub base_code { my ($h_codes) = @_; for my $h_planet (values %$h_codes) { for my $a_aa (values %$h_planet) { # for my $codon ( @$a_aa ) { print $codon, "\n"; } } } }

{ earth => { proline => ["CCA", "CCC", "CCG", "CCT"], serine => ["TCA", "TCC", "TCG", "TCT"], }, mars => { proline => ["ZXZ", "ZXX", "ZXQ", "ZXW"], serine => ["QWZ", "QWX", "QWW"], }, } TCA TCC TCG TCT CCA CCC CCG CCT QWZ QWX QWW ZXZ ZXX ZXQ ZXW

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^2: printing complex data structures (values)
by AnomalousMonk (Archbishop) on Jul 24, 2017 at 16:35 UTC

    Using values allows more direct access to nested hash values, but pay heed to haukex's update note here discussing the fact that keys allows control of the ordering of access to hash values, and this may be very important, in particular for large data structures. (See also perldsc.)


    Give a man a fish:  <%-{-{-{-<

      In this case it's IMHO better to use a hash-slice @hash{LIST}

      ... it'll give me full control over the order since I can include any LIST not just sorted keys.

      But still basically operating on values...

      sub base_code { my ($h_codes) = @_; for my $h_planet ( @$h_codes{ sort keys %$h_codes }) { for my $a_aa ( @$h_planet{ sort keys %$h_planet}) { for my $codon ( @$a_aa ) { print $codon, "\n"; } } } }

      or for convenience

      sub sorted_values { my $h_ref =shift; return @$h_ref{ sort keys %$h_ref } } sub base_code2 { my ($h_codes) = @_; for my $h_planet ( sorted_values $h_codes ) { for my $a_aa ( sorted_values $h_planet ) { for my $codon ( @$a_aa ) { print $codon, "\n"; } } } }

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

Re^2: printing complex data structures (values)
by stevieb (Canon) on Jul 24, 2017 at 15:40 UTC

    ++ for using values() and eliminating all of the extraction. I use values() so infrequently I tend to forget it exists :)

Re^2: printing complex data structures (values)
by ic23oluk (Sexton) on Jul 24, 2017 at 15:51 UTC
    Also a good hint, thank you!!