Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Is it possible to get reference to scalar based on scalar name

by sundialsvc4 (Abbot)
on Sep 05, 2012 at 18:08 UTC ( #991905=note: print w/replies, xml ) Need Help??

in reply to Is it possible to get reference to scalar based on scalar name

To put it another way ... create a hash, each element of which is a reference to, either the object itself, or another hash which contains various references that you need when accessing it.   Thanks to the “auto-vivification” features of Perl, that can be quite easy to do.   For example:

my $objs; $$objs{'widget1'}{'widget'} = $widget1; $$objs{'widget1'}{'object'} = $object1; ...

If in this example $widget1 and $object1 contain references to this-or-that, now the various hash-entries thus created contain another reference to those same things, whose reference-count is now at least 2.   Perl automatically recognized $objs to be a hash, automatically created an element for 'widget1', then automatically caused that element to be another hash, and inserted 'widget' and 'object' elements into that.

Note that the syntax $$objs{'widget1'} is exactly equivalent to $objs->{'widget1'}, as you prefer.

This hashing technique now lets you build an arbitrary directory of entries which allow you to map any name that you receive to everything that you need to know about it.   It also allows you to recognize, through exists(), if you have encountered a name that you have no information about.   There are many, many ways to write this, but the differences are unimportant; the central idea is the same.

(If the search needs to be case-insensitive, simply use lc()to lowercase the string before using it as a hash-key, and likewise ensure that all inserted keys are lowercased.)

  • Comment on Re: Is it possible to get reference to scalar based on scalar name
  • Download Code

Replies are listed 'Best First'.
Re^2: Is it possible to get reference to scalar based on scalar name
by mrider (Beadle) on Sep 05, 2012 at 18:17 UTC
    Yes, that's precisely what I'll do. I don't know why I didn't think of using a hash. As I say in my other post, I guess I was too close to the problem to see the obvious answer. Thank you for taking the time to respond!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://991905]
[1nickt]: pryrt yes, I see. There is no way to differentiate without forcing to a string and all sort of weird stuff. It is enough. User 42 can get creative if s/he wishes.
[chacham]: i sent him a private message expressing my displeasure.
[1nickt]: chacham It was worse than 2-1 ! almost 4-1 !
[jdporter]: Dang. No good example of how to use IPC::Run's run() in its simplest mode?
[LanX]: him or her! ;)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (15)
As of 2017-05-24 20:54 GMT
Find Nodes?
    Voting Booth?