In Perl, is it better to use a module than to require a file?

前端 未结 4 1338
抹茶落季
抹茶落季 2020-12-04 09:26

Another question got me thinking about different methods of code reuse: use vs. require vs. do

I see a lot of posts here where

4条回答
  •  温柔的废话
    2020-12-04 10:01

    There is a major preference for using use, because it happens at an earlier state BEGIN {} during compilation, and the errors tend to be propagated to the user at a more appropriate time. It also calls the sub import {} function which gives the caller control over the import process. This is something that is heavily used. You can get the same effect, by calling the specific namespace's import, but that requires you to know the name of the namespace, and the file, and to code the call to the subroutine... which is a lot more work. Conversely, use, just requires you to know the namespace, and then it requires the file with the matching namespace -- thus making the link between namespaces and files less of an conscious to the user.

    Read perldoc -f use, and perldoc -f require, for more information. Per perldoc -f use:
    use is the same as BEGIN { require Module; Module->import( LIST ); } Which is just a lot more ugly.

提交回复
热议问题