4

我正在学习 perl,当我尝试做面向对象时,我遇到了错误,这是代码,Test.pm

 #!/usr/bin/perl 

package Test;

sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "SSN is $self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

sub setFirstName {
    my ( $self, $firstName ) = @_;
    $self->{_firstName} = $firstName if defined($firstName);
    return $self->{_firstName};
}

sub getFirstName {
    my( $self ) = @_;
    return $self->{_firstName};
}
1;

和 test.pl

#!/usr/bin/perl
use Test;
$object = Test::new( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor.
$firstName = $object->getFirstName();

print "Before Setting First Name is : $firstName\n";

# Now Set first name using helper function.
$object->setFirstName( "Mohd." );

# Now get first name set by helper function.
$firstName = $object->getFirstName();
print "Before Setting First Name is : $firstName\n";

当我尝试运行时,它显示了一些这样的错误,

Can't locate object method "new" via package "Test" at test.pl line 2.

这个面向对象的程序有什么错误?

4

3 回答 3

7

Test 是一个模块的名称,它是 perl 标准发行版的一部分。您use Test正在加载它而不是您的测试;为您的模块选择另一个名称。

于 2013-10-01T04:46:51.323 回答
4

您的问题是您已经在默认包含目录的其他位置有一个名为 Test.pm 的模块。

尝试运行 perl:

perl -I./ test.pl

这会将目录 ./ (即当前目录)添加到 @INC 的开头(这是一个特殊变量,包含要从中加载模块的目录列表)。

于 2013-10-01T04:50:13.920 回答
3

Test是一个预先存在的 Perl 模块,它位于当前目录的@INC之前。Test.pm(您加载错误Test.pm。)

将您的模块重命名为MyTest或类似名称。

于 2013-10-01T04:47:33.967 回答