Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: printing complex data structures

by stevieb (Canon)
on Jul 24, 2017 at 15:04 UTC ( [id://1195872]=note: print w/replies, xml ) Need Help??


in reply to printing complex data structures

First, don't use prototypes unless you know why you need them. Also, in Perl, you do not need to pre-declare your subroutines like you do in C for instance.

Now, you were trying to use $planet as a hash reference, but it's actually a string (which you extract when you call keys %$h_ref. So, you have to pass in a reference to a hash in the call to base_code(), then inside the sub, you need to use the key name $planet as the key to the encompassing $h_ref to extract out the data you want:

use strict; use warnings; 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'] }; base_code (\%codes); sub base_code { my $h_ref = $_[0]; for my $planet (keys %$h_ref){ for my $aa (keys %{ $h_ref->{$planet} }){ for my $codon (@{ $h_ref->{$planet}{$aa} }){ print $codon, "\n"; } } } }

Output:

CCA CCC CCG CCT TCA TCC TCG TCT ZXZ ZXX ZXQ ZXW QWZ QWX QWW

Replies are listed 'Best First'.
Re^2: printing complex data structures
by haukex (Archbishop) on Jul 24, 2017 at 15:25 UTC
    you do not need to pre-declare your subroutines like you do in C for instance.

    Nitpick: You do in the case of the OP's code, because otherwise Perl will complain "main::base_code() called too early to check prototype" and the code won't work (because Perl doesn't know to take a reference to %codes as the argument). In general, if a sub has a prototype, Perl needs to see its declaration before it is called. But of course I agree with the advice to not use a prototype in the first place, in which case the issue becomes moot :-)

      Ah, yes, of course :) Thanks for pointing that out.

Re^2: printing complex data structures
by ic23oluk (Sexton) on Jul 24, 2017 at 15:34 UTC
    thank you very much!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-03-29 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found