0

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 = {};
Koomba27
  • 3
  • 3

2 Answers2

1

The anonymous hash is the {} part. It returns a reference which can be stored in a scalar variable, like in your example:

my $addr = {};

To see the structure, you can print it with Data::Dumper:

use Data::Dumper;
print Dumper $addr;

It might show you something like:

$VAR1 = {
          'c' => 1,
          'a' => 2
        };

You access the hash keys using the arrow operator:

print $addr->{"a"}

Like how you would access a regular hash, but with the arrow operator in between.

You can dereference the reference by putting a hash sigil in front

%$addr

# compare %addr  %$addr
#          hash   hashref dereferenced
TLP
  • 66,756
  • 10
  • 92
  • 149
0

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->{$_}";
}
Dave Cross
  • 68,119
  • 3
  • 51
  • 97