export vs export_ok in perl

前端 未结 2 380
野性不改
野性不改 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:07

    Let's say I have a package MyPackage that uses @EXPORT.

    #this is MyPackage.pm
    package MyPackage;
    @EXPORT = qw(do_awesome_thing);
    
    sub do_awesome_thing { ... }
    
    sub be_awesome { ... }
    

    Now, when I use MyPackage in my code,

    #this is myscript.pl
    use MyPackage;
    
    do_awesome_thing(); #works
    
    be_awesome(); #doesn't work
    MyPackage::be_awesome(); #works
    

    do_awesome_thing gets automatically exported to my code from MyPackage, without me having to say "give this to me". be_awesome isn't exported (and it won't be exported with @EXPORT_OK either, I'm just showing that part to get you clear on what "exporting" gives us).

    On the other hand, if I have a package MyOtherPackage that uses @EXPORT_OK,

    #this is MyOtherPackage.pm
    package MyOtherPackage;
    @EXPORT_OK = qw(do_awesome_thing);
    
    sub do_awesome_thing { ... }
    
    sub be_awesome { ... }
    

    and then try

    #this is mynewscript.pl
    use MyOtherPackage;
    
    do_awesome_thing(); #doesn't work
    MyOtherPackage::do_awesome_thing(); #works, as always
    

    the line calling do_awesome_thing directly won't work. This is because putting something in @EXPORT_OK says "give this to my users only if they ask for it". Since we've just said use MyOtherPackage without explicitly asking for do_awesome_thing to be imported here, it doesn't get imported, and is accessible only by specifying the package name.

    The way you ask for do_awesome_thing to be imported is to say use MyOtherPackage qw(do_awesome_thing) in the second line of mynewscript.pl above. This says import that module and make do_awesome_thing available directly. After that, the fourth line in mynewscript.pl above will start working.

    Note that the user can specify use MyPackage qw(do_awesome_thing) with the first package also, and in that case, anything else in the @EXPORT list won't be exported, only do_awesome_thing will be. So, except for the default case of use PackageName;, @EXPORT and @EXPORT_OK behave similarly. In the default case, anything in @EXPORT gets thrown into the user's script automatically, while @EXPORT_OK is more polite and doesn't export anything.

提交回复
热议问题