1
votes

I am new to Perl, and I am trying something with a hash. I have a hash of hashes like below:

%HoH =   
(
    "Test1" => { checked => 1, mycmd => run1 },
    "Test2" => { checked => 1, mycmd => run2 },
)

Using the below code I will get the output given below:

for $family ( keys %HoH ) 
{
    print "$family: ";
    for $role ( keys %{ $HoH{$family} } ) 
    {
        print "$role=$HoH{$family}{$role} ";
    }
    print "\n";
}

Output:

Test1: checked=1 mycmd=run1 
Test2: checked=1 mycmd=run2

My question is, how can I access individual checked & cmd separately? By accessing separately, I can compare what is checked and do my task.

2
What do you mean? Isnt $HoH{"Test1"}{checked} what you want? - Karthik T
Doesn't your output say "cmd", not "mycmd"? Do you mean, see if Test1 is checked, then see what the command is? Something like if ($HoH{Test1}->{checked}) { system($HoH{Test1}{cmd}) }? - Charles Engelke
Also, please begin your code with use strict; and use warnings; and fix anything they complain about. It will make your code cleaner and easier to debug. (In particular, you should add quotes around the strings run1 and run2 and declare your loop variables as local with for my $var (...).) - Ilmari Karonen

2 Answers

3
votes

It's pretty straight-forward to just use the keyword(s) literally:

%HoH =   
(
    "Test1" => { checked => 1, cmd => run1 },
    "Test2" => { checked => 1, cmd => run2 },
);
if ($HoH{"Test1"}{checked}) {
print "Test1 is Checked with cmd: " . $HoH{"Test1"}{cmd} . "\n";
}

Test1 is Checked with cmd: run1

Did I understand your question correctly?

1
votes
for my $family ( keys %HoH )
{
    if ($HoH{$family}->{checked}) {
         # Do what you want...
    }
}