Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: using ref to hash of hash effectively

by eyepopslikeamosquito (Bishop)
on Dec 27, 2020 at 04:00 UTC ( #11125779=note: print w/replies, xml ) Need Help??


in reply to using ref to hash of hash effectively

Perhaps the definitive reference for this sort of thing is in the standard Perl docs: perldsc (Perl Data Structures Cookbook). After you read and understand that, you should be on your way. For some light relief, some sample code to crudely dump ... then "pretty print" your hash of hashes:

use strict; use warnings; use Data::Dumper; my $weapons_ref = { dagger => { cost => 8, damage => 4, armor => 0 }, shortsword => { cost => 10, damage => 5, armor => 1 }, warhammer => { cost => 25, damage => 6, armor => 2 }, longsword => { cost => 40, damage => 7, armor => 0 }, greataxe => { cost => 74, damage => 8, armor => 0 }, }; print Dumper($weapons_ref); # Print by hand so it looks a bit prettier. :) for my $weapon ( sort keys %{$weapons_ref} ) { printf "%-14.14s\n", $weapon . ( '-' x 20 ); for my $attr ( sort keys %{ $weapons_ref->{$weapon} } ) { printf " %-8.8s:%3d\n", $attr, $weapons_ref->{$weapon}{$attr}; } }

which produces:

$VAR1 = { 'dagger' => { 'cost' => 8, 'armor' => 0, 'damage' => 4 }, 'greataxe' => { 'damage' => 8, 'armor' => 0, 'cost' => 74 }, 'warhammer' => { 'armor' => 2, 'damage' => 6, 'cost' => 25 }, 'shortsword' => { 'damage' => 5, 'armor' => 1, 'cost' => 10 }, 'longsword' => { 'cost' => 40, 'damage' => 7, 'armor' => 0 } }; dagger-------- armor : 0 cost : 8 damage : 4 greataxe------ armor : 0 cost : 74 damage : 8 longsword----- armor : 0 cost : 40 damage : 7 shortsword---- armor : 1 cost : 10 damage : 5 warhammer----- armor : 2 cost : 25 damage : 6

I leave summing by cost and other attributes as an exercise for the reader ... just in case it's a homework question. :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2021-06-16 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (77 votes). Check out past polls.

    Notices?