rsriram has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I have few functions, which I am using in different perl scripts. In every script, I am placing the function repetatively. Is there any way, with which I can store all the functions in a separate file and call them into the script? What I am looking for is something similar to calling header files in C or C++ (like stdio.h or iostream.h).

Replies are listed 'Best First'.
Re: Calling functions from other scripts
by quester (Vicar) on Mar 19, 2007 at 05:47 UTC
    What you want is a perl module file. The basics are documented in the documentation of perlmod under "Modules" .

    Here is a trivial example: This script uses say_hello:

    #! perl -w use strict; use warnings; use mystuff; mystuff::say_hello "world";

    ... and say_hello is defined in this script, which should be saved as "mystuff.pm" in the same directory.

    #! perl -w use warnings; use strict; package mystuff; sub say_hello { print "hello " . shift() . "\n"; } 1
    If you run the first script above with

    $ perl -w example.pl
    it will print

    hello world
Re: Calling functions from other scripts
by bobf (Monsignor) on Mar 19, 2007 at 05:48 UTC
Re: Calling functions from other scripts
by Zaxo (Archbishop) on Mar 19, 2007 at 05:35 UTC

    Sure, put them in a seperate file and use, require or do.

    After Compline,
    Zaxo

Re: Calling functions from other scripts
by Sixtease (Friar) on Mar 19, 2007 at 08:22 UTC
    Hello. quester's example is great. But if you don't like the idea of having to write mystuff::hello, you can either omit the package mystuff line in the module, which may not be a best practice or you can useExporter; @EXPORT_OK=('hello');
Re: Calling functions from other scripts
by johngg (Canon) on Mar 19, 2007 at 09:49 UTC
    You could have a look at this post in another thread for a small, real-world example of module use. Note that my module uses the POSIX module which is part of the standard Perl distribution.

    I hope this is of use.

    Cheers,

    JohnGG