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

I create a hash from a file using format similar to /etc/group:

process:text:action:email

ie:

syslogd:syslogd daemon::user@host.com

I create hash:

@fields = split /:/; $process = shift @fields; $hash{$process}{'TEXT'} = shift @fields; $hash{$process}{'ACTION'} = shift @fields; $hash{$process}{'EMAIL'} = shift @fields;

And I can do:

print "$hash{'syslogd'}{'EMAIL'}\n"; and get "user@host.com"

But how do I reference not the key ($process) but the sub-key (for lack of better term) in the above hash in a foreach?

foreach my $processKey (sort keys %hash) { print "$_"; foreach my $hashKey (sort keys $hash{$processKey}) { print ":$daemontable{$processKey}{$hashKey}\n"; } }

This ofcourse doesn't work. I don't understand how to get at the "EMAIL", "ACTION", "TEXT" fields of a hash other then specifying them manually (which defeats the purpose)

The idea is that I don't need to manually add code everytime I add a new sub-key into the foreach loop.

I apologize if my terminology is off.

Replies are listed 'Best First'.
Re: Referencing dynamic hash elements
by davorg (Chancellor) on Jan 03, 2001 at 18:30 UTC

    Your problem is the line

    foreach my $hashKey (sort keys $hash{$processKey})

    $hash{$processKey} is a reference to a hash and keys requires an actual hash. Therefore, all you need to do is to dereference the hash reference before passing it to keys

    foreach my $hashKey (sort keys %{$hash{$processKey}})

    It's also worth pointing out that had you been running with -w and use strict then perl would have told you what the problem was.