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

后端 未结 8 1453
陌清茗
陌清茗 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:21

    I know the question specifically says "functions", but I get this post high up in search when I look for "perl include", and often times (like now) I want to include variables (in a simple way, without having to think about modules). And so I hope it's OK to post my example here (see also: Perl require and variables; in brief: use require, and make sure both "includer" and "includee" files declare the variable as our):

    $ perl --version
    
    This is perl, v5.10.1 (*) built for i686-linux-gnu-thread-multi ...
    
    $ cat inc.pl
    use warnings;
    use strict;
    
    our $xxx = "Testing";
    
    1;
    
    $ cat testA.pl 
    use warnings;
    use strict;
    
    require "inc.pl";
    our $xxx;
    
    print "1-$xxx-\n";
    print "Done\n";
    
    $ perl testA.pl 
    1-Testing-
    Done
    
    
    $ cat testB.pl 
    use warnings;
    use strict;
    
    our $xxx;
    print "1-$xxx-\n";
    
    $xxx="Z";
    print "2-$xxx-\n";
    
    require "inc.pl";
    
    print "3-$xxx-\n";
    print "Done\n";
    
    $ perl testB.pl 
    Use of uninitialized value $xxx in concatenation (.) or string at testB.pl line 5.
    1--
    2-Z-
    3-Testing-
    Done
    

提交回复
热议问题