export vs export_ok in perl

前端 未结 2 367
野性不改
野性不改 2020-12-29 04:00

I can not understand what is the difference/use case of EXPORT_OK vs EXPORT.
Most resources mentions something in the lines of:

2条回答
  •  隐瞒了意图╮
    2020-12-29 04:23

    From the fine Exporter manual:

    • use YourModule;
      This imports all the symbols from YourModule's @EXPORT into the namespace of the use statement.
    • use YourModule ();
      This causes perl to load your module but does not import any symbols.
    • use YourModule qw(...);
      This imports only the symbols listed by the caller into their namespace. All listed symbols must be in your @EXPORT or @EXPORT_OK, else an error occurs. The advanced export features of Exporter are accessed like this, but with list entries that are syntactically distinct from symbol names.

    So, if you use @EXPORT and someone does the usual use YourModule;, then you've just polluted their namespace with everything in @EXPORT. But, if you use @EXPORT_OK, they have to specifically ask for things to be imported so the person using your module has control over what happens to their namespace.

    The difference is really a matter of who controls what gets into the user's namespace: if you use @EXPORT then the module being used does, if you use @EXPORT_OK then the code doing the import controls their own namespace.

    Of course, you could always say use Whatever(); to keep impolite modules from polluting your namespace but that's ugly and you shouldn't have to kludge around rude code that wants to scribble all over your namespace.

提交回复
热议问题