How do I use subroutines from other perl files in my program?

You have a subroutine or collection of subroutines that you want to use in multiple Perl programs.

Solution: Require files

One solution is to put those subroutines into a separate file, for example one called, and require that file. But be aware that there are downsides to this technique, not the least of which is namespace collision. Have a look at creating your own module instead.

If you still want to examine require, lets look at

    sub add_ten($) {
        my ($number) = @_;
        return ($number + 10);

Note that you need the 1; at the end of the file. This is because Perl needs the last expression in the file to return a true value.

In the program in which you want to call the subroutines, you need to require

    use strict;
    use warnings;

    require '';

    print "Enter a number: ";
    my $number = <>;
    chomp $number;

    print "Adding ten: " . add_ten($number) . "\n";

If the require file ( is in another directory you will need to specify the absolute path:

    require "/home/me/";

You don't need to worry about recursive requiring (e.g. requiring a file that requires the current file), Perl will handle everything.

See also

    perldoc -f require
    perldoc -q require
    Chapter 2, Schwartz Randal L. "Perl Objects, References & Modules" O'Reilly 2003
    perldoc perlmod
    perlfaq7 - How do I create a module
    perlootut - Object-Oriented Programming in Perl Tutorial
Revision: 1.7 [Top]