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

Hello Monks, I defined a class like this:
use Class::Struct; struct A => { b => '%',
It is contained in another class, where I try to access b:
$self->{ReferenceToA}->b($key)
Perl quits with "Not a CODE reference". I find that interesting, because when I debug my code, it says:
p ($self->{ReferenceToA}->can('b')) CODE(0xe91738)
Thanks for enlightening me! Martin

Replies are listed 'Best First'.
Re: Class::Struct - Not a CODE referemce
by almut (Canon) on Jun 07, 2010 at 13:07 UTC

    Works fine for me:

    #!/usr/bin/perl -l use strict; use warnings; use Class::Struct; struct A => { b => '%', }; my $obj = new A; print $obj->can('b'); $obj->b('foo', "bar"); # call setter print $obj->b('foo'); use Data::Dumper; print Dumper $obj; __END__ CODE(0x8b5570) bar $VAR1 = bless( { 'A::b' => { 'foo' => 'bar' } }, 'A' );

    (also works when I use $self->{ReferenceToA} in place of $obj)

    What happens when you run this example?

      Your example works for me too. Sorry. Apparently I took the error out of my code while reducing it to a simpler test case. My production code still exits with "Not a CODE Reference". I tried debugging it, but I do not understand why it crashes while evaluating the if-expression.
      1357==>b if ($self->{TT}->call_category($key) != undef) 1358 { 1359 # Do something, never reached 1360 }
      use Data::Dumper; print Dumper $key $VAR1 = 'AN-AM-BA';
      print Dumper $self->{TT}->call_category $VAR1 = { 'DU-EX-TA' => 16, '*-CM-*' => 145, # Lots more, but not the value of $key. '*-VY-*' => 132 };
      print Dumper $self->{TT}->call_category($key) $VAR1 = undef;
      n Not a CODE reference at ...
      Do you have any pointer what's wrong here?
        # Lots more, but not the value of $key

        Where do you set the hash entry (in case you expect it to be set)?

        Anyhow, as you can tell from the $VAR1 = undef in

        print Dumper $self->{TT}->call_category($key) $VAR1 = undef;

        when you try to fetch non-existent entries, you just get undef (not too surprising, actually).  However, it's not the accessor that causes the "Not a CODE reference" issue, but something later in code you haven't shown (otherwise the error would be thrown before Dumper gets the undef).  In other words, it might not have anything to do with Class::Struct.