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

How would i construct a hash of usernames that stores an array and each of the elements in the array is another hash. And how would I access it later?
($cpu,undef) = split(".", $5); ($hours, $minutes) = split(":", $7); $time = ($hours * 60) + $minutes; %one = ( pid => $1, mem => $4, cpu => $cpu, time => $time, tty => $8, cmd => $9 ); push $users{$2}, $one;

Replies are listed 'Best First'.
Re: Data Structures
by lhoward (Vicar) on Jun 05, 2000 at 01:09 UTC
    First off you should check out perldsc, the Perl Data Structures Cookbook. It contains discussion and good examples of how to make many perl datastructures (lists of lists, list of hashes, hashes of lists, hashes of hashes, etc...).

    Here's some quick code that defines the hash, inserts an element, and extracts an element out of the structure. Hopefully this will be enough to get you started along the path to Perl datastructure enlightenment:

    my %users; $users{foo}=[{a=>1,b=>2},{a=>2,b=>3}]; my $x=$users{foo}[1]{a}; #$x==2 at this point
Re: Data Structures
by Corion (Patriarch) on Jun 05, 2000 at 01:09 UTC

    You can read the long answer under perlman:perlref.

    For your specific example, this should work as follows (untested) :

    # ... your stuff here, to load $2 and %one with data push $users{$2}, \%one; ... my $user = $users{$key}; foreach $value ("pid", "cmd", "mem") { print %$user{$value}, " "; };

Re: Data Structures
by buzzcutbuddha (Chaplain) on Jun 05, 2000 at 17:17 UTC
    The Camel Book has a great discussion of Data Structures: Lists of List, Lists of Hashes,
    Hashes of Lists, Hashes of Hashes, and points you in the direction of learning more. I
    probably read that section at least once a week so it sinks in. Very handy in loading values from
    a database where you want to manipulate the values very fast (since hashes are faster and safer than
    working with the data in the database directly):
    while (!$recordset->eof) { # code to set scalars equal to fields in $recordset $hashofrecordset{$id} = { foo => $foo, bar => $bar, baz => $baz, +}; }
    foreach $outerkey ( sort keys %hashofrecordset ) { print "\n$hashofrecordset{$outerkey}\n"; foreach $innerkey ( sort keys %{ $hashofrecordset{$outerkey} + }) { print "\t$hashofrecordset{$outerkey}{$innerkey}\n"; } print "\n"; }
    That's the basic idea anyway. take care!