一个文件下有两个文件,pm和pl。如果运行pl文件,pm包调用不成功

文件目录?

/home/wh/perlstudy/perl2/Person/Student.pm
/home/wh/perlstudy/perl2/Person/person.pl

学生.pm

package Student;
use strict;
use warnings FATAL => 'all';
# use utf8;
# binmode(STDIN,"encoding(gbk)");
sub new
{
    my $class = shift;
    my $self = {
        _name => shift, _rank  => shift, };
    # Print all the values just for clarification.
    print "??????  $self->{_name}n";
    print "?????? $self->{_rank}n";

    bless $self, $class;
    return $self;
}
sub studentRank {
    my ( $self, $name ) = @_;
    $self->{_name} = $name if defined($name);
    return $self->{_name};
}
sub studentName {
    my( $self ) = @_;
    return $self->{_name};
}
1;

人.pl

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
# use utf8;
# binmode(STDOUT,"encoding(gbk)");
BEGIN(push @INC,"/home/wh/perlstudy/perl2/Person/");
use Student;
my$object = Student->new( "Ana", "9th");
# name which is set using constructor.
my$name = $object->studentName();
print "Name set using constructor is : $namen";
# name set using helper function.
$object->studentRank( "Anastasia" );
# getting name set by helper function.
$name = $object->studentName();
print "?? set using helper is : $namen";

我得到:

BEGIN '@' 之后的原型:在 perlson.pl 第 6 行推送 @INC,"/home/wh/perlstudy/perl2/Person/"。

想解决使用 perl 模块以外的@INC.

回答

BEGIN是代码块,所以需要大括号:

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
# use utf8;
# binmode(STDOUT,"encoding(gbk)");
BEGIN {
    push @INC, "/home/wh/perlstudy/perl2/Person/";
}
# rest of person.pl goes here

或者-I在调用 Perl 时使用该标志:

perl -I/home/wh/perlstudy/perl2/Person/ person.pl

这样做的好处是您不必对路径进行硬编码,但每次都必须重新键入。(或者为它创建一个别名或 shell 脚本。)

或使用 lib:

use lib "/home/wh/perlstudy/perl2/Person/";

最后,您可以将 Perl 模块安装在 Perl 默认查找模块的位置,但在开发过程中,每次更改Student.pm.


以上是一个文件下有两个文件,pm和pl。如果运行pl文件,pm包调用不成功的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>