Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Data Dump / Tool To View Hash Structure Easily?

by rjt (Curate)
on Sep 09, 2013 at 23:46 UTC ( [id://1053122]=note: print w/replies, xml ) Need Help??


in reply to Data Dump / Tool To View Hash Structure Easily?

You mentioned having trouble "figuring out how to access information from a hash nested within another hash", and asked for an example. Once you learn this syntax, you'll be wanting to use it all over the place.

For purposes of a concrete example, say you have a hash of users. Their usernames are keys, but the values are hash refs with additional information. It would look something like this (written here by hand, but not too different from a Data::Dump output):

%users = ( rjt => { home => '/home/rjt', uid => 1000, shell => '/bin/bash', groups=> [ qw< sudo lpadmin > ], }, jdlev => { home => '/home/jdlev', uid => 1001, shell => '/bin/csh', groups=> [ qw< users lpadmin > ], }, );

Note that the "groups" key refers to an array reference with the groups the user belongs to. Here are some examples of accessing the various data:

print "rjt's uid is $users{rjt}{uid}\n"; local $" = ', '; # List separator print "jdlev is a member of: @{$users{jdlev}{groups}}.\n"; push @{$users{jdlev}{groups}}, 'sudo'; # jdlev now belongs to sudo as +well

As for how to dump the data, Data::Dump gets my vote, most often anyway. I have some local debugging libraries that do various other data munging tasks to create more concise dumps in certain cases, but 99% of the time I could live with Data::Dump. It not being core doesn't concern me because none of the dump() calls survive to production code in my case.

use strict; use warnings; omitted for brevity.

Replies are listed 'Best First'.
Re^2: Data Dump / Tool To View Hash Structure Easily?
by jdlev (Scribe) on Sep 11, 2013 at 00:18 UTC
    Thanks for the great examples, they were very helpful. I have a question though. When you're using perl hashes, what is the difference between declaring a hash as "%hash" and "$hash"?

    I'm not sure why, but I've tried to print by using  $hash{113}{id} \n; and it won't put out anything for some reason? Meanwhile, Dumper works just fine and spews data all over the place?

    I love it when a program comes together - jdhannibal

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-19 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found