开发者

How to make a hash of objects in perl

I would like to be able to store objects in a hash structure so I can work with the name of the object as a variable. Could someone help me make a sub new{ ... } routine that creates a new object as member of a hash? I am not exactly sure how to go about doing this or how to refer to and/or use the object when it is st开发者_如何学Pythonored like this. I just want to be able to use and refer to the name of the object for other subroutines.

See my comment in How can I get name of an object in Perl? for why I want to do this.

Thank you


Objects don't really have names. Why are you trying to give them names? One of the fundamental points of references is that you don't need to know a name, or even what class it is, to work with it.

There's probably a much better way to achieve your task.

However, since objects are just references, and references are just scalars, the object can be a hash value:

my %hash = (
    some_name => Class->new( ... ),
    other_name => Class->new( ... ).
    );

You might want to check out a book such as Intermediate Perl to learn how references and objects work.


Don't quite understand what you are trying to do. Perhaps you can provide some concrete examples?

You can store objects into hashes just like any other variable in perl.

my %hash = ( );
$hash{'foo'} = new Foo(...);
$hash{'bar'} = new Bar(...);

Assuming you know the object stored at 'foo' is a Foo object and at 'bar' is a Bar object, then you can retrieve the objects from the hash and use it.

$hash{'foo'}->foo_method();
$hash{'bar'}->bar_method();

You may want to programmatically determine this behavior at run time. That's assuming that you are sticking with this naming scheme.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜