簡體   English   中英

如何在Perl中的另一個模塊子內部調用一個模塊子

[英]How to call one module sub inside another module sub in Perl

我已經在/my_project/ABC/下創建了Perl模塊。 ABC文件夾包含三個子例程模塊: Build.pmConfig.pmOperation.pm 我需要從Config.pm訪問Operation.pm中的一個通用子例程,但是當我嘗試時會拋出

“ configureTheRepository”不是由ABC :: Config模塊導出的。

這是調用堆棧。

Operation.pm

    package ABC::Operation;

    use strict;
    use warnings;

    use Term::ANSIColor qw(:constants);
    use File::Basename qw(dirname);
    use Exporter qw(import);
    use Term::ANSIColor qw( colored );
    use Data::Dumper qw(Dumper);
    use JSON::PP;
    use File::Basename qw(dirname);
    use Cwd  qw(abs_path);
    use ABC::Config qw(configureTheRepository);

    our @EXPORT = qw(commonFunc)

   sub commonFunc{
      #handle logic
    }
1;

配置文件

    package ABC::Config;

    use strict;
    use warnings;

    use Term::ANSIColor qw(:constants);
    use File::Basename qw(dirname);
    use Exporter qw(import);
    use Cwd  qw(abs_path);
    use Cwd  qw(abs_path);
    use ABC::Operation qw(commonFunc); #Compilation failed when i insert this line.if i removed this my script will execute and but in runtime throws undefined commonFunc.

   our @EXPORT = qw(configureTheRepository);

   sub configureTheRepository{
      #handle logic
    }

1;

請讓我知道我在哪里弄錯了。

存在循環依賴關系。 use語句在編譯時完成。 這意味着在運行任何實際代碼之前。 因此,當您啟動程序時,首先要做的是進入ABC::Operation ,將發生以下情況:

  • 掃描ABC :: Operation for use語句
  • 加載期限:: ANSIColor
    • 解析開關到Term :: ANSIColor
    • scan Term :: ANSIColor for use語句...
  • 解析切換回ABC :: Operation
  • 加載File :: Basename
    • 解析切換到File :: Basename
    • 掃描File :: Basename
  • 解析切換回ABC :: Operation
  • ...其中一些
  • 加載ABC :: Config
    • 解析切換到ABC :: Config
    • 掃描ABC :: Config以獲取use聲明...
  • 將女巫解析回ABC :: Operation
    • 從Term :: ANSIColor,File :: Basename,Exporter和Cwd import內容; 這些不會再次加載,因為Perl之前已經加載了它們。 它僅將符號導入到當前的ABC :: Config命名空間中
    • 從ABC :: Config import功能commonFunc ; 再次,它也已經被加載,因此它不會再次加載
    • 引發錯誤,因為此時ABC :: Config尚未完成解析,並且尚未導出commonFunc符號

這有點令人困惑,但這表明您的體系結構已損壞。 如果事情很普遍,那么它們肯定可以放在一個共同的包裝中。 但是該通用軟件包不能使用任何使用它的軟件包。 如果真是這樣,無論使用什么定義,它也變得很普遍。

解決的辦法是重新考慮哪些功能在哪里。 找到最小的零件,並將它們放在一個包裝中。 這就是其他所有軟件包共享的東西。 然后在需要的地方使用它。 使用此功能的下一個功能不應相互融合。只有最后一級可以將所有這些功能結合在一起。 依賴樹之所以稱為樹。 在那里圍成一圈是行不通的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM