I'm able to successfully create the $tv_horse object, but when I try to use the 'set_name' or 'name' methods I get a 'Not a HASH reference at ./test_objects.pl line 22.' I've used the debugger and it looks to me like the object is a reference to a hash:#!/usr/bin/perl -w use strict; { package Animal; sub named { # Constructor of instance - Objects my $class = shift; # first argument is class name die "already an object. $!" if ref($class); # only instances are references my $name = shift; # 2nd arg is the object's identity my $self = {Name => $name, Color => $class->default_color}; bless \$self, $class; # create the object } sub set_name { my $object = shift; # first argument s/b an instance my $name = shift; # 2nd parm s/b the new animal name if (ref $object) { $object->{Name} = $name; } else {die "It's a class variable, $!";} } sub name { my $self = shift; ref $self ? $self->{Name} : "Just another $self"; # Not an instance, hence no name } } { package Horse; our @ISA = qw(Animal); sub default_color {"brown";} } my $tv_horse = Horse->named("Mr. Ed"); print $tv_horse->name, " is ",$tv_horse->name,"\n"; $tv_horse->set_name("Mister Ed");
If I use class, not instance, methods this all works correctly of course. Any suggestions?DB<7> x $object 0 Horse=REF(0x13080) -> HASH(0x191d8d0) 'Color' => 'brown' 'Name' => 'Mr. Ed'
In reply to 'Not a HASH reference' error using Objects by irwin
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |