Home > Enterprise >  Perl OOP cant see new method
Perl OOP cant see new method

Time:10-07

Started to learn Perl, trying OOP, created main program and package. While trying to create object of class package receive an error in main file. Calling a new method inside package works.

Main.pl

use strict;
use warnings;
BEGIN { unshift @INC , '.';}
use Stack01Lib;

print "Hello, World!\n";

my @stack = new Stack01Lib();

Stack01Lib.pm

  package Stack01Lib;

  use strict; 
  use warnings;

  sub new {
    my($class) = shift;
    my $self = { };

    bless $self, $class;

    return $self;
  }

1;  

print "Loaded\n";

After compilation

Can't locate object method "new" via package "Stack01Lib" (perhaps you forgot to load "Stack01Lib"?) at D:\Projects\perl\hello\Main.pl line 26.
Loaded
Hello, World!

CodePudding user response:

You're not loading the file you showed, possibly because of this bug:

BEGIN { unshift @INC , '.';}

Relative paths in @INC are relative to the current work directory. You want script's directory, so it should be

use FindBin qw( $RealBin );
BEGIN { unshift @INC, $RealBin; }

Simpler:

use FindBin qw( $RealBin );
use lib $RealBin;

The code you posted is otherwise fine. It does not result in the error you posted.

  •  Tags:  
  • perl
  • Related