In Perl, what is the difference between use and require for loading a module?

后端 未结 4 565
一生所求
一生所求 2021-02-03 22:24

What is the difference between doing use My::Module and require My::Module?

4条回答
  •  [愿得一人]
    2021-02-03 22:37

    The use function:

    use ModuleName;
    

    is equivalent to the following code using the require function:

    BEGIN {
        require ModuleName;
        ModuleName->import;
    }
    

    The BEGIN block causes this code to run as soon as the parser sees it. The require loads the module or dies trying. And then the import function of the module is called. The import function may do all sorts of things, but it is common for it to load functions into the namespace that used it (often with the Exporter module).

    It is important to note that import will not be called in this case:

    use ModuleName ();
    

    In that case, it is equivalent to

    BEGIN {
        require ModuleName;
    }
    

提交回复
热议问题