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, |
In reply to Re: Use Objects as Hash Values?
by Athanasius
in thread Use Objects as Hash Values?
by cmikel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |