Tweet

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 common_functions.pl.

common_functions.pl:

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

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 common_functions.pl:

    #!/usr/bin/perl
    use strict;
    use warnings;

    require 'common_functions.pl';

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

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

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

    require "/home/me/common_functions.pl";

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
[Top]