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

Honored Monks.
I'm using Randal Schwartz's text Perl Objects, References & Modules to learn OOP with Perl. I've made it up to chapter 9, where I've encountered a problem with the exercise that I can't figure out.
Here's the code:
#!/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");
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:
DB<7> x $object 0 Horse=REF(0x13080) -> HASH(0x191d8d0) 'Color' => 'brown' 'Name' => 'Mr. Ed'
If I use class, not instance, methods this all works correctly of course. Any suggestions?

Replies are listed 'Best First'.
Re: 'Not a HASH reference' error using Objects
by kyle (Abbot) on Jan 14, 2009 at 02:47 UTC

    Welcome to the Monastery, irwin.

    The problem is on this line:

    bless \$self, $class;

    Here, $self is a scalar which contains a reference to a hash. What you bless, is a reference to $self (\$self) instead of $self. The line should be:

    bless $self, $class;
      I just knew it was gonna be something simple! thanks for the solution and thanks for the warm welcome. I think I'm going to like it here. :-)
Re: 'Not a HASH reference' error using Objects
by missingthepoint (Friar) on Jan 14, 2009 at 03:20 UTC

    I don't have any advice, and I think kyle nailed it, but I just wanted to say welcome :). And, stick around if you can - you can learn a lot here.


    Life is denied by lack of attention,
    whether it be to cleaning windows
    or trying to write a masterpiece...
    -- Nadia Boulanger