suppose $my_ref = \$hash{'mary'}; #my_ref is a reference point to a hash element.
....
later, how can I use $my_ref to retrieve the key of the hash element that it points to? How to get the string "mary" from $my_ref ?
I ask this question because I have several groups of username lists, some usernames appear in several groups that consume memory. Therefore, I decided to create a common list of usernames, and let these groups retain a link only to the corresponding username, not to the username.
eg. initially
%group1 = {'mary'=>1, 'luke'=1,'tom'=1,...} %group2 = {'mary'=>1, 'sam'=1,'tom'=1,...}
Here you see 'mary' and 'tom' are shown in both group1 and group2 , which consume memory. (note: the value in this example is not important to me, the value here is only because the data structure is a hash). To reduce the amount of memory, I want all user names to be stored in the general list:
%common_hash = {'mary'=>1, 'luke'=1,'tom'=1,'sam'=1...}; $ref1 = \$common_hash{'mary'}; $ref2 = \$common_hash{'luke'}; $ref3 = \$common_hash{'tom'}; $ref4 = \$common_hash{'sam'};
Groups
save only the hash element link:
%group1 = {$ref1=>1, $ref2=1,$ref3=1,...}; %group2 = {$ref1=>1, $ref4=1,$ref3=1,...};
I think this approach can save a lot of memory because:
- one username is stored in memory once several times;
- groups store a link (an integer), not a string (in my case, the length of each username is an average of 30 bytes, and each integer is only 4 bytes (32-bit system) or 8 bytes (64-bit system.)) (BTW, correct me if the integer doesn't use 4 bytes or 8 bytes.)
- using the link, I can immediately get the username without looking for it.
But how can I get a username from a group?
If I use @my_ref = keys %group1 , I think I get the value "mary", but not "mary".
$result = $($my_ref[0]);