views:

80

answers:

2

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 stored 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 http://stackoverflow.com/questions/3605685/how-to-get-name-of-object-in-perl for why I want to do this.

Thank you

+4  A: 

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.

brian d foy
See my comment in http://stackoverflow.com/questions/3605685/how-to-get-name-of-object-in-perl for why I want to do this.
Feynman
Add a `name` method to your objects and set that when you instantiate the object.
CanSpice
I saw your other posts, but I still don't know what you are trying to get at. I think you're fixated on a method instead of an end.
brian d foy
You can't merely add instance data to all objects (at least not without acrobatics and decorating). These objects might be from any class, not necessarily one that Feynman gets to create.
brian d foy
@Feynman: your design is upside down; you should derive filenames from some method in the classes (perhaps defined in the base class, where it uses `ref($this)` to create a filename), rather than in some extra data stored outside the class. Please consider getting a book.
Ether
+1  A: 

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.

It's best not to use indirect object notation when calling methods. So instead of `new Foo(...);`--use `Foo->new(...);` See perlobj ( http://perldoc.perl.org/perlobj.html#Indirect-Object-Syntax ) for more info.
daotoad