Home > OS >  How to print key value of hash reference in perl?
How to print key value of hash reference in perl?

Time:08-18

I am using a perl module called Nmap::Parser and stuggling with how to handle hash references, I am new to these. A call to one of the functions in this module is instructed like this:

A basic call to scripts() returns a list of the names of the NSE scripts run for this port. If $name is given, it returns a reference to a hash with "output" and "contents" keys for the script with that name, or undef if that script was not run. The value of the "output" key is the text output of the script. The value of the "contents" key is a data structure based on the XML output of the NSE script.

How am I supposed to access these key values, I tried the following:

        my $script = $service->scripts();
        foreach my $key ( keys %$script) { 
            print $key, " => ", $script->{$key},"\n";
            foreach my $seckey ( keys %$key ) {
                print $seckey, " => ", $key->{$seckey},"\n";
            }
        }

And this was my output:

ldap-rootdse

Thanks!

CodePudding user response:

keys returns strings, so $key is a string, so $key->{$seckey} is wrong.

If you have a HoH, you want

foreach my $key ( keys %$script ) { 
    my $val =  $script->{$key};
    foreach my $inner_key ( keys %$val ) {   # %$val, not %$key
        my $inner_val = $val->{ $inner_key };
        ...
    }
}
  • Related