There are two files, pm and pl under one file. If you run the pl file, the pm package call is unsuccessful

Viewed 68

File Directory:

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

Student.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;

person.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 : $name\n";
# name set using helper function.
$object->studentRank( "Anastasia" );
# getting name set by helper function.
$name = $object->studentName();
print "名字 set using helper is : $name\n";

I get:

Prototype after '@' for BEGIN : push @INC,"/home/wh/perlstudy/perl2/Person/" at perlson.pl line 6.

Want to solve the use of perl modules other than @INC.

1 Answers

BEGIN is a code block, so you need curly braces:

#!/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

Or you use the -I flag when you call Perl:

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

This has the advantage that you don't have to hard-code the path, but you'll have to re-type it each time. (Or make an alias or shell script for it.)

Or use lib:

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

Finally you could install your Perl module in a place where Perl looks for modules by default, but during development you'll have to do that each time you make changes to Student.pm.

Related