Hello:
I'm trying to write my first class at WeBWorK, and I need help. Here is the error I get:
Undefined subroutine &Term::Compute called at line 31 of [TMPL]/macros/term.pl
Died within Term::getVar called at line 22 of (eval 1417)
What should I include in the package file, so I can use Compute() in Numerics context in a subroutine of the class?
Carl Yao
Portland Community College
File 1: term.pl
package Term;
sub new {
my $class = shift;
my $self = {
_coefficient => shift,
_var0 => shift,
_var1 => shift
};
bless $self, $class;
return $self;
}
sub getVar {
my( $self ) = @_;
my $coe = $self->{_coefficient};
my @var0 = @{ $self->{_var0} };
return Compute("$coe*$var0[0]")->reduce;
}
1;
File 2: test.pl
DOCUMENT();
loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"PGML.pl",
"term.pl",
"PGcourse.pl",
);
TEXT(beginproblem());
#############################
Context("Numeric");
$a = 5;
@var0 = ('x',2,1,0);
@var1 = ('y',0,1,2);
$object = new Term( $a, ~~@var0, ~~@var1);
$b = $object->getVar();
ENDDOCUMENT();
Within a package, if an unqualified function (that isn't in the
CORE::
namespace) is called, it is assumed to be a method in the package being defined. So when you use Compute()
in the return
statement at the end of getVar()
that Compute()
is considered to be a method of Term
. Note how the error message indicates it is looking for Term::Compute()
. You need to qualify the function call to get the correct Compute
. So use
return main::Compute("$coe*$var0[0]")->reduce;in order to use the
Compute()
from the main::
namespace.
Thank you!
Carl Yao