bashperlwhois

Perl: Using data from an anonymous hash


I am adding on to another developers code, we are both new to perl I am trying to take a list of IPs and run it through whois. I am unsure how to access the data in the anonymous hash, how do I use it? He told me the data was stored inside one. This is the only instance I could find mentioning a hash:

## Instantiate a reference to an anonymous hash (key value pair)
my $addr = {};

Solution

  • Here is an anonymous hash:

    my $anon_hash = {
      key1 => 'Value 1',
      key2 => 'Value 2',
      key3 => 'Value 3',
    }
    

    If you want to access an individual value:

    my $value = $anon_hash->{key1};
    say $anon_hash->{key2};
    

    If you want to update an individual value:

    $anon_hash->{key3} = 'New value 3';
    

    If you want to add a new key/value pair:

    $anon_hash->{key4} = 'Value 4';
    

    You can also use all of the standard hash functions (e.g. keys()). You just need to "deference" your hash reference - which means putting a '%' in front of it.

    So, for example, to print all the key/value pairs:

    foreach my $key (keys %$anon_hash) {
      say "$key : $anon_hash->{$_}";
    }