in reply to Use Objects as Hash Values?

Hello cmikel, and welcome to the Monastery!

As NetWallah says, you need to chomp the keyboard input string before using it as a hash key. NetWallah’s proposed OO design, using a House class as a container for Room objects, is a good approach. However, your original design can also be made to work with a few tweaks:

#! perl use strict; use warnings; package Room { sub new { my $class = shift; my $self = { id => shift, name => shift, detail => shift, }; return bless $self, $class; } } my %houserooms = ( kitchen => Room->new(1, 'kitchen', 'sleek and modern'), den => Room->new(2, 'den', 'board games and more'), ); print "\nEnter room (or \"quit\"):\n"; chomp(my $roomcmd = <>); while ($roomcmd ne 'quit') { print $houserooms{$roomcmd}->{detail} // "$roomcmd not found"; print "\n\nEnter room (or \"quit\"):\n"; chomp($roomcmd = <>); }

Typical output:

18:22 >perl 607_SoPW.pl Enter room (or "quit"): kitchen sleek and modern Enter room (or "quit"): den board games and more Enter room (or "quit"): bedroom bedroom not found Enter room (or "quit"): quit 18:23 >

Note that an object is a blessed reference, so there is no need to use syntax like this:

%houserooms = ( kitchen => { House->new("1","kitchen","sleek and modern") }, ... );

which takes a House object (already a reference!), puts it into another (anonymous) hash, and stores a reference to that hash as the value corresponding to the “kitchen” key in the hash %houserooms.

See perlreftut, perlref, perlootut, and perlobj.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Use Objects as Hash Values?
by cmikel (Novice) on Apr 15, 2013 at 13:49 UTC
    Thank you both very much! Both your answers helped! For now I think I might stick with my original design - but it was helpful to see how to build an additional class as the container for my other objects.