in reply to Re: Code from perlboot not working as expected
in thread Code from perlboot not working as expected

Thanks. Putting in the single quotes means I can leave Strict in. But I'm afraid it doesn't clear the SCALAR part of the output. If anyone can help in that direction, I'd love to know more.

Regards,

John Davies
  • Comment on Re^2: Code from perlboot not working as expected

Replies are listed 'Best First'.
Re^3: Code from perlboot not working as expected
by kennethk (Abbot) on May 17, 2010 at 14:49 UTC
    Ahh, I missed that part of the OP - sorry. That's happening because the first object in @_ when you invoke a method via an object is the object, not the package name. Thus your $class variable contains the scalar reference and when you print $class you stringify that reference. One way of handling that is to use ref. Something like:

    my $self = shift; my $class = ref($self) || $self;

    If $self contains a blessed reference, ref will return the package name. If it contains a string, ref will return undef and hence the || will return the original string.

    I personally prefer perltoot to perlboot. But both are certainly worth working through.

      Perfect. I actually tried perltoot first, but got horribly confused by constructs like my $class = ref($self) || $self;. Thanks to your explanation, I now understand that, too. I also see from trying the suggestion in Re^3: Code from perlboot not working as expected how to get a reference to the name, another point that was causing me confusion.

      Thanks and regards,

      John Davies
Re^3: Code from perlboot not working as expected
by Anonymous Monk on May 17, 2010 at 14:51 UTC
    $class is a reference to the object and I believe that's what you get when you print out a reference. Just dereference it (note the double $): print "a $$class goes ", $class->sound, "!\n"; Kevin Sigl
      Dereferencing will get you the value contained in the scalar reference, but the spec expects the package name. The code

      print "a $$class goes ", $class->sound, "!\n";

      will yield the output

      a Mr. Ed goes neigh!

      not the expected

      a Horse goes neigh!

      It will also fail outright if the code is invoked statically, with the error under strict:

      Can't use string ("Horse") as a SCALAR ref while "strict refs" in use