How do I include functions from another file in my Perl script?

后端 未结 8 1461
陌清茗
陌清茗 2020-11-28 04:46

This seems like a really simple question but somehow my Google-Fu failed me.

What\'s the syntax for including functions from other files in Perl? I\'m looking for s

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:23

    Perl require will do the job. You will need to ensure that any 'require'd files return truth by adding

    1;
    

    at the end of the file.

    Here's a tiny sample:

    $ cat m1.pl 
    use strict;
    sub x { warn "aard"; }
    1;
    
    $ cat m2.pl 
    use strict;
    require "m1.pl";
    x();
    
    $ perl m2.pl 
    aard at m1.pl line 2.
    

    But migrate to modules as soon as you can.

    EDIT

    A few benefits of migrating code from scripts to modules:

    • Without packages, everything occupies a single namespace, so you may hit a situation where two functions from separate files want the same name.
    • A package allows you to expose some functions, but hide others. With no packages, all functions are visible.
    • Files included with require are only loaded at run time, whereas packages loaded with use are subject to earlier compile-time checks.

提交回复
热议问题