Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

I'm creating a server in Perl, and I'm trying to make a hash with all clients that are connected to the server. For practical purposes, I'm setting the IO::Socket::INET object, as returned by new() as key of the hashe. So, I can add refhashes like $clients->{$socket}->{transferedBytes} += 10.

The problem is: how can I access, say, the foo method from the object? In a foreach loop (foreach (keys %{$clients})), how can I access either the methods from IO::Socket::INET on $_ and my defined $_->{transferedBytes}?

I hope you can understand my doubt. An advice on how I could store sockets on hashes/arrays would be nice.

Thanks a lot.

Replies are listed 'Best First'.
Re: Hash of IO::Socket::INET objects
by sacked (Hermit) on Jul 09, 2004 at 18:16 UTC
    Without using Tie::RefHash, you can't (documented in perlfaq4, "How can I use a reference as a hash key?"). When you use a reference as a hash key, it is stringified (turned into a string representation of the memory address), after which the key cannot be used as a reference. For example, one of your hash keys will look something like IO::Socket::INET=GLOB(0x80665b4) when examined.

    You could change your data structure to store your objects in an array of hashes:
    # in some loop my $client= $server->accept(); push @clients => { socket => $client, bytesTransferred => 0, };
    Given that you were originally using a hash, the order probably doesn't matter, but for what it's worth, an array will keep the objects in the order originally inserted.

    BTW, searching for 'object hash key' and 'reference hash key' yielded the following nodes related to your question:

    Problem using object references as hash keys
    using references as keys in a hash.
    array reference as hash key
    If a hash key is a reference...

    --sacked