aoiee aoiee - 2 years ago 117
Perl Question

Perl - how to use the reference id?

When printing an object:

my $hash = {};
print($hash); # it outputs some sort of hex identifier: HASH(0X3A8154)

How can I use this hex identifier as a string or a key?

my $map = {};
my $object = {};
$map->{$object_id} = $object; # where $object_id is the string result of $object when printed

Answer Source

What you are getting is a stringification of a reference, of a hash reference in this case.

So you get a string you want, and can assign it to a variable (my $id = "$hashref";)

perl -wE'$hr = {a=>1, b=>2}; say $hr; $s = "$hr"; say $s'

prints HASH(0x2398d48) twice.

So in your example with your hash reference $object you can do

$map->{"$object"} = $object;

and in fact you can do

$map->{$object} = $object;

since the hashref $object gets stringified in order to get a string needed for a key.

However, this does not seem like a good idea at all. For one thing, how can one distinguish the keys (always HASH(num)) to various $objects? A key is used to identify the value associated with it and here there'll be some "random" numbers.

Why not come up with id's for your objects that are meaningful and carry information on their own? You can also use a data structure that has $objects in it directly, since they are scalars. Or write a class so $objects are actual objets; then you can set up any data/attributes you want.

Can you explain the purpose in more detail, for a more concrete idea?

  I can't find explanation of stringification in docs. See this post, for example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download