Search code examples
perlcallsubroutine

If a subroutine is in the same directory as my main function, how do I call it?


Alright I'm rewriting this to elaborate more. I am fairly new to Perl & programming so please bear with me. Essentially, I want to know how run one or more files (I am guessing modules?) inside of the main .pl file when they come from within the same directory. My code works fine with them all plugged in at the bottom of my file as a subroutine but not if I pull the subroutines out and turn them into modules.


Solution

  • Here's a couple of steps to hopefully get you started. This exports some subs to package MyModule.

    Firstly Create MyModule.pm in the same directory as your main program. For example:

    package MyModule;
    use warnings; use strict;
    
    sub foo {
        my $p = shift;
        print "foo called with param: $p\n";
        bar();
    }
    
    sub bar {
        print "bar called\n";
    }
    
    1; # don't delete this line
    

    Then to load and call subs from this package from your main program:

    #/usr/bin/perl                                                                                                                                            
    use warnings; use strict;
    
    use File::Basename qw(dirname);
    use lib dirname(__FILE__); # prepend source directory to the include path                                                                                 
    
    use MyModule;
    
    MyModule::foo(42);
    

    The statement use lib dirname(__FILE__) is prepending the source directory of the main program to the module include path.