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

Hi all, I'm a beginner to Perl. I've got several scripts that have some functions and global variables in common. Can I separate these shared functions and variables in a single file that I can "#include" in each of my scripts? Thanks for your help.

Replies are listed 'Best First'.
Re: Perl equivalent of C's #include
by ar0n (Priest) on Aug 25, 2000 at 05:00 UTC
    Yes, you can put them in a seperate file and use the file like so:
    require 'file.pl';
    You'll need to add a "1;" on the last line of the file so it'll return true.
    update: read the perldoc's on require and use.

    -- ar0n || Just Another Perl Joe

Re: Perl equivalent of C's #include
by athomason (Curate) on Aug 25, 2000 at 09:35 UTC
    Your problem is much more easily and cleanly solved by the above answers, so use those. This is just an academic comment ;-).

    <don't do this>

    Perl can actually use the C preprocessor if you invoke the interpreter with the -P flag. Then your #includes and other such C pragmas will work. However, as is typical for Perl, the kludgely preprocessor directives have been superceded by more Perlish (i.e., easier, safer, more huggable) constructs. #define constants should use the const module; #includes should be replaced by real modules with use or require. Since these aren't preprocessor directives, #ifdefs are unnecessary.

    </don't do this>

Re: Perl equivalent of C's #include
by davorg (Chancellor) on Aug 25, 2000 at 10:38 UTC

    If these functions and global variables are goingto be used by a number of different scripts then it might be worth making them into a proper module. Then you'll be able to include it by using:

    use MyStuff;
    --
    <http://www.dave.org.uk>

    European Perl Conference - Sept 22/24 2000, ICA, London
    <http://www.yapc.org/Europe/>
Re: Perl equivalent of C's #include
by Cirollo (Friar) on Aug 25, 2000 at 17:35 UTC
Re: Perl equivalent of C's #include
by tenatious (Beadle) on Aug 25, 2000 at 05:01 UTC
    yep. You can use require "./myvariables.pl"; at the top of your script. It imports everything in the perl library into your script. There are fancier ways to do the same thing, but this is probably the easiest.