開始學習 Perl,嘗試 OOP,創建主程式和包。嘗試創建類包的物件時在主檔案中收到錯誤。在包內呼叫新方法有效。
主檔案
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";
編譯后
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!
uj5u.com熱心網友回復:
你沒有加載你顯示的檔案,可能是因為這個錯誤:
BEGIN { unshift @INC , '.';}
中的相對路徑@INC是相對于當前作業目錄的。你想要腳本的目錄,所以它應該是
use FindBin qw( $RealBin );
BEGIN { unshift @INC, $RealBin; }
更簡單:
use FindBin qw( $RealBin );
use lib $RealBin;
您發布的代碼沒有問題。它不會導致您發布的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316261.html
標籤:perl
