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?

In reply to 'Not a HASH reference' error using Objects by irwin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.